1. 程式人生 > >python爬蟲基礎知識(一)--Urllib.request

python爬蟲基礎知識(一)--Urllib.request

explain:The urllib.request module defines functions and classes which help in opening URLs (mostly HTTP) in a complex world — basic and digest authentication, redirections, cookies and more.


1.urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
開啟網址url,可以是一個字串或者Request物件。
比如:

file=urllib.request.urlopen("http://www.baidu.com")
print(file.read())#讀取所有內容賦給一個字串
print(file.readline())#一行
print(file.readlines())#讀取所有內容賦給一個列表
file.info()#獲取當前環境有關的資訊
file.getcode()#獲取返回的狀態碼
file.geturl()#獲取源網頁地址

2.urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)


Copy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen().

這個函式是打來一個url並且儲存到本地檔案,返回的是一個tuple物件,同時這個函式在執行的過程中,還會有一定的緩衝,用urllib.request.urlcleanup()這個函式就可以清除快取。

filname=urllib.request.urlretrieve("http://www.baidu.com",filename="data2.html")
urllib.request.urlcleanup()
print(filname)

3.模擬瀏覽器修改報頭


方法1:
使用build_opener()進行。

import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-agent'
, 'Mozilla/5.0')] opener.open('http://www.example.com/')

方法2:
使用add_header()。

import urllib.request
req = urllib.request.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
r = urllib.request.urlopen(req)

4.urllib.parse.quote(string, safe=’/’, encoding=None, errors=None)
解決url編碼問題,預設為utf-8,safe表示可以忽略的字元,error預設為replace,meaning invalid sequences are replaced by a placeholder character.

key="粑粑"
key_code=urllib.parse.quote(key)
print(key_code)
url="http://www.baidu.com/s?wd="+key_code

5.get請求步驟
構建對於的url–>以對應的URL為引數,構建Request物件–>
通過urlopen()開啟構建的Request物件–>後續操作

import urllib.request,urllib.parse
url="http://www.baidu.com/s?wd="
key="重慶"
key_code=urllib.parse.quote(key)
urlall=url+key_code
req=urllib.request.Request(urlall)
data=urllib.request.urlopen(req).read()
print(data)

6.post請求步驟
1)設定URl網址
2)構建表單資料,使用urllib.parse.urlkencode進行編碼處理
3)建立Request物件
4)add_header()新增頭資訊
5)使用urllib.request.urlopen()開啟提交併處理


7.代理伺服器設定

def use_proxy(proxy_address,url):
    import  urllib.request
                      proxy=urllib.request.ProxyHandler({'http':proxy_address})
    opener=urllib.request.build_opener(proxy,urllib.request.HTTPHandler)
    urllib.request.install_opener(opener)#全域性預設的opener物件
    data=urllib.request.urlopen(url).read().decode('utf-8')
    return  data
proxy_add="112.74.32.237:6666"
data=use_proxy(proxy_add,"http://www.baidu.com")
print(len(data))