官方文檔地址:https://docs.python.org/3/library/urllib.htmljavascript
其主要包括一下模塊:html
urllib.request 請求模塊java
urllib.error 異常處理模塊python
urllib.parse url解析模塊json
urllib.robotparser robots.txt解析模塊服務器
urllib.request.urlopencookie
urlopen參數以下:app
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None
經常使用參數:ide
url:訪問的地址,通常不僅是地址。函數
data:此參數爲可選字段,特別要注意的是,若是選擇,請求變爲post傳遞方式,其中傳遞的參數須要轉爲bytes,若是是咱們只須要經過 urllib.parse.urlencode 轉換便可:
import urllib.parse import urllib.request data = bytes(urllib.parse.urlencode({"word": "python"}), encoding= 'utf8') response = urllib.request.urlopen("http://xxxxx", data=data) print(response.read().decode('utf-8'))
timeout:設置網站的訪問超時時間
其餘參數:
context 參數:它必須是 ssl.SSLContext 類型,用來指定 SSL 設置。
cafile 和 capath 兩個參數:是指定CA證書和它的路徑,這個在請求 HTTPS 連接時會有用。
cadefault 參數:如今已經棄用了,默認爲 False
urlopen返回對象提供方法:
read() , readline() ,readlines() , fileno() , close() :對HTTPResponse類型數據進行操做。
info():返回HTTPMessage對象,表示遠程服務器返回的頭信息。
getcode():返回Http狀態碼。
geturl():返回請求的url。
1 import urllib.request 2 response = urllib.request.urlopen('http://python.org/') 3 4 #查看 response 的返回類型 5 print(type(response)) 6 7 #查看反應地址信息 8 print(response) 9 10 #查看頭部信息_1 11 print(response.info()) 12 13 #查看頭部信息_2(http header) 14 print(response.getheaders()) 15 16 #輸出頭部屬性信息 17 print(response.getheader("Server")) 18 19 #查看響應狀態信息_1 20 print(response.status) 21 22 #查看響應狀態信息_2 23 print(response.getcode()) 24 25 #查看響應url地址 26 print(response.geturl()) 27 28 #輸出網頁源碼 29 page = response.read() 30 print(page.decode('utf-8'))
1 import urllib.request 2 headers = {'Host': 'www.xicidaili.com', 3 'User-Agent': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT6.0)', 4 'Accept': r'application/json, text/javascript, */*; q=0.01', 5 'Referer': r'http://www.xicidaili.com/', } 6 7 req = urllib.request.Request('http://www.xicidaili.com/', headers=headers) 8 response = urllib.request.urlopen(req) 9 html = response.read().decode('utf-8') 10 print(html)
Request參數以下:
urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
經常使用參數:
url:訪問的地址。
data:此參數爲可選字段,其中傳遞的參數須要轉爲bytes,若是是字典只須要經過 urllib.parse.urlencode 轉換便可:
headers:http相應headers傳遞的信息,構造方法:headers 參數傳遞,經過調用 Request 對象的 add_header() 方法來添加請求頭。
其餘參數:
origin_req_host :指的是請求方的 host 名稱或者 IP 地址。
unverifiable :用來代表這個請求是不是沒法驗證的,默認是 False 。意思就是說用戶沒有足夠權限來選擇接收這個請求的結果。若是沒有權限,這時 unverifiable 的值就是 True 。
method :用來指示請求使用的方法,好比 GET , POST , PUT 等
1 import urllib.request 2 3 #建立自定義函數 4 def use_proxy(proxy_addr,url): 5 6 #使用urllib.request.ProxyHandle()設置代理服務器參數 7 proxy = urllib.request.ProxyHandler({'http':proxy_addr}) 8 9 #使用urllib.request.build_opener()建立一個自定義的opener()對象 10 #第一個參數爲代理信息,第二個參數爲urllib.request.HTTPHandler類 11 opener = urllib.request.build_opener(proxy,urllib.request.HTTPHandler) 12 13 #爲了方便,使用urllib.request.install_opener()建立全局默認的opener對象 14 urllib.request.install_opener(opener) 15 #urllib.request.urlopen()打開指定網址進行爬取,將函數的調用賦值給data 16 data = urllib.request.urlopen(url).read().decode('utf-8') 17 return data 18 19 proxy_addr = '61.135.217.7:80' 20 data = use_proxy(proxy_addr,"http:4//www.baidu.com") 21 print(len(data))
1 import http.cookiejar, urllib.request 2 3 cookie = http.cookiejar.CookieJar() 4 handler = urllib.request.HTTPCookieProcessor(cookie) 5 opener = urllib.request.build_opener(handler) 6 response = opener.open('http://www.baidu.com')
1 filename = 'cookie.txt' 2 cookie = http.cookiejar.MozillaCookieJar(filename) 3 handler = urllib.request.HTTPCookieProcessor(cookie) 4 opener = urllib.request.build_opener(handler) 5 response = opener.open('http://www.baidu.com') 6 cookie.save(ignore_discard=True, ignore_expires=True)
1 import http.cookiejar, urllib.request 2 cookie = http.cookiejar.MozillaCookieJar() 3 cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True) 4 handler = urllib.request.HTTPCookieProcessor(cookie) 5 opener = urllib.request.build_opener(handler) 6 response = opener.open('http://www.baidu.com') 7 print(response.read().decode('utf-8'))
用 try-except來捕捉異常,
主要的錯誤方式就兩種 :
URLError(錯誤信息)
HTTPError(錯誤編碼)
1 try: 2 data=urllib.request.urlopen(url) 3 print(data.read().decode('utf-8')) 4 except urllib.error.HTTPError as e: 5 print(e.code) 6 except urllib.error.URLError as e: 7 print(e.reason)