request.Request類
如果想要在請求的時候增加一些請求頭郊闯,那么就必須使用request.Request類來實現(xiàn)舆蝴,比如增加一個user-agent斩例,
示例代碼:
from urllib import request,parse
url = 'https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false'headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6788.400 QQBrowser/10.3.2767.400',
'Referer':'https://www.lagou.com/jobs/list_python%E7%88%AC%E8%99%AB?oquery=python&fromSearch=true&labelWords=relative',
'Connection':'keep-alive'}
data = {
'first':'true',
'pn': 1,
'kd':'python'}
req = request.Request(url,headers=headers,data=parse.urlencode(data).encode('utf-8'),method='POST')
resp=request.urlopen(req)
print(resp.read().decode('utf-8'))
ProxyHandler處理器(代理設(shè)置)
很多網(wǎng)站會監(jiān)測某一個段時間某個IP的訪問次數(shù)過多不是正常人峭火,他會禁用這個IP哥放,所以需要設(shè)置代理服務(wù)器,就算IP被禁了還能繼續(xù)爬咖摹。
- 代理的原理:在請求目的的網(wǎng)站之前评姨,先請求代理服務(wù)器,然后讓代理服務(wù)器去請求目的網(wǎng)站萤晴,代理服務(wù)器拿到目的網(wǎng)站的數(shù)據(jù)后吐句,在轉(zhuǎn)發(fā)給我們的代碼
- http:httpbin.rog:這個網(wǎng)站可以方便的查看http請求的一些參數(shù)
- 在代碼中使用代理:
- 使用
urllib.request.ProxyHandler
傳入一個代理,這個代理是一個字典店读,字典的key依賴于代理服務(wù)器能夠接受的類型嗦枢,一般是http
或者https
,值是ip:port
屯断。 - 使用上一步創(chuàng)建的
handler
文虏,以及request.build_opener
創(chuàng)建一個opener
對象。 - 使用上一步創(chuàng)建的
opener
殖演,調(diào)用open
函數(shù)氧秘,發(fā)起請求
示例代碼如下:
from urllib import request
#沒有使用代理url = 'http://httpbin.org/ip'# resp=request.urlopen(url)# print(resp.read())#使用代理#1.使用proxyHandler.傳入代理handlerhandler = request.ProxyHandler({"http":"183.129.207.80:12085"})
#2.使用上面的handler構(gòu)建一個openeropener = request.build_opener(handler)
#3.使用opener去發(fā)送請求resp=opener.open(url)
print(resp.read())