urllib介紹
- urllib.request 提供了一個(gè) urlopen 函數(shù),來(lái)實(shí)現(xiàn)獲取頁(yè)面。支持不同的協(xié)議、基本驗(yàn)證、cookie、代理等特性。
- urllib 有兩個(gè)版本 urllib 以及 urllib2。
urllib2 能夠接受 Request 對(duì)象,urllib 則只能接受 url。 - urllib 提供了 urlencode 函數(shù)來(lái)對(duì)GET請(qǐng)求的參數(shù)進(jìn)行轉(zhuǎn)碼,urllib2 沒(méi)有對(duì)應(yīng)函數(shù)。
- urllib 拋出了 一個(gè) URLError 和一個(gè) HTTPError 來(lái)處理客戶端和服務(wù)端的異常情況。
urllib中包括四個(gè)模塊
urllib.request,urllib.error,urllib.parse,urllib.robotparser
urllib.request可以用來(lái)發(fā)送request和獲取request的結(jié)果
urllib.error包含了urllib.request產(chǎn)生的異常
urllib.parse用來(lái)解析和處理URL
urllib.robotparse用來(lái)解析頁(yè)面的robots.txt文件
url, \目標(biāo)url
data=None, \默認(rèn)為None表示是get請(qǐng)求,如果不為None說(shuō)明是get請(qǐng)求
timeout 設(shè)置請(qǐng)求的超時(shí)時(shí)間
cafile=None, capath=None, cadefault=False,:證書(shū)相關(guān)參數(shù)
context=None :忽略證書(shū)認(rèn)證
urlopen不能添加請(qǐng)求頭response = request.urlopen(url=url,timeout=10)
urllib.request.urlopen post請(qǐng)求攜帶參數(shù)
data = {
'name' = 'name',
'age' = 18
}
bianliang = urllib.parse.urlencode(data).encode()
request = urllib.request.Request(url=url, data=bianliang,headers=headers)
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
content = response.read().decode('utf-8')
print(content)
requests是python實(shí)現(xiàn)的最簡(jiǎn)單易用的HTTP庫(kù),建議爬蟲(chóng)使用requests
獲取某個(gè)網(wǎng)頁(yè)
import requests
r = requests.get("https://api.github.com/events")
print(r)
各種請(qǐng)求
# 發(fā)送一個(gè) HTTP POST 請(qǐng)求:
r = requests.post("http://httpbin.org/post",data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete') # 發(fā)送一個(gè) HTTP delete 請(qǐng)求:
r = requests.head('http://httpbin.org/get') # 發(fā)送一個(gè) HTTP head 請(qǐng)求:
r = requests.options('http://httpbin.org/get') # 發(fā)送一個(gè) HTTP options 請(qǐng)求:
requests提供了params關(guān)鍵字參數(shù)來(lái)傳遞參數(shù)
parameter = {
"key1":"value1",
"key2":"value2"
}
response2 = requests.get("http://httpbin.org/get",params = parameter)
print(response2.url)
#話可以將一個(gè)列表作為值傳入
parameter = {"key2":["value21","value22"]}
#注意字典里值為 None 的鍵都不會(huì)被添加到 URL 的查詢字符串里。
parameter = { "key2":None}
POST請(qǐng)求
發(fā)送一些編碼為表單形式的數(shù)據(jù)——非常像一個(gè) HTML 表單。要實(shí)現(xiàn)這個(gè),只需簡(jiǎn)單地傳遞一個(gè)字典給 data 參數(shù)。數(shù)據(jù)字典在發(fā)出請(qǐng)求時(shí)會(huì)自動(dòng)編碼為表單形式:通過(guò)在發(fā)送post請(qǐng)求時(shí)添加一個(gè)data參數(shù),這個(gè)data參數(shù)可以通過(guò)字典構(gòu)造成,這樣對(duì)于發(fā)送post請(qǐng)求就非常方便
payload = {
"key1":"value1",
"key2":"value2"
}
response = requests.post("http://httpbin.org/post",data = payload)
print(response.text)
響應(yīng)
可以通過(guò)response獲得很多屬性,例子如下
import requests
response = requests.get("http://www.baidu.com")
print(type(response.status_code),response.status_code) #< class 'int'> 200
print(type(response.headers),response.headers) # 頭部信息
print(type(response.cookies),response.cookies) #<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
print(type(response.url),response.url) # <class 'str'> http://www.baidu.com/
print(type(response.history),response.history) # <class 'list'> []
Cookie
如果某個(gè)響應(yīng)中包含一些 cookie,可以快速訪問(wèn)它們:
import requests
response = requests.get("http://www.baidu.com")
print(response.cookies)
for key,value in response.cookies.items():
print(key+"="+value)
要想發(fā)送的cookies到服務(wù)器,可以使用 cookies 參數(shù):
import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
response = requests.get(url, cookies=cookies)
print(response.text)
超時(shí)
可以告訴 requests 在經(jīng)過(guò)以 timeout 參數(shù)設(shè)定的秒數(shù)時(shí)間之后停止等待響應(yīng)?;旧纤械纳a(chǎn)代碼都應(yīng)該使用這一參數(shù)。如果不使用,的程序可能會(huì)永遠(yuǎn)失去響應(yīng):
response1 = requests.get('http://github.com', timeout=100)
print(response1) #<Response [200]>
response2 = requests.get('http://github.com', timeout=0.1)
print(response2) # 報(bào)錯(cuò)ReadTimeout
SSL 證書(shū)驗(yàn)證
Requests 可以為 HTTPS 請(qǐng)求驗(yàn)證 SSL 證書(shū),就像 web 瀏覽器一樣。SSL 驗(yàn)證默認(rèn)是開(kāi)啟的,如果證書(shū)驗(yàn)證失敗,Requests 會(huì)拋出 SSLError:
response = requests.get('https://requestb.in')
print(response) # 拋出異常 SSLError:
response = requests.get('https://github.com', verify=True)
print(response)
為了避免這種情況的發(fā)生可以通過(guò)verify=False但是這樣是可以訪問(wèn)到頁(yè)面,但是會(huì)提示:InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)
解決方法:
import requests
from requests.packages import urllib3
urllib3.disable_warnings() # 就這一句就可以解決
response = requests.get("https://www.12306.cn",verify=False)
print(response.status_code)
可以為 verify 傳入 CA_BUNDLE 文件的路徑,或者包含可信任 CA 證書(shū)文件的文件夾路徑:
requests.get('https://github.com', verify='路徑')
或者將其保存在會(huì)話中:
s = requests.Session()
s.verify = '路徑'
代理
如果需要使用代理,你可以通過(guò)為任意請(qǐng)求方法提供 proxies 參數(shù)來(lái)配置單個(gè)請(qǐng)求:
import requests
proxies = {
"http": "http://10.10.1.10:8000",
"https": "http://10.10.1.10:8080",
}
requests.get("http://example.org", proxies=proxies)