Python爬蟲之Urllib.request.Request

Request簡介


urlopen()方法可以實現最基本的請求的發起,但如果要加入Headers等信息,就可以利用Request類來構造請求。
使用方法爲:
 

urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

參數解析

 

參數 作用
url 要請求的url
data data必須是bytes(字節流),如果是字典,要用urllib。parse模塊理的urllencode()編碼
headers headers是一個字典類型,是請求頭。可以在構造請求時通過headers參數直接構造,也可以通過調用請求實例的add_header()方法添加。可以通過請求頭僞裝瀏覽器,默認User-Agent是Python-urllib。要僞裝火狐瀏覽器,可以設置User-Agent爲Mozilla/5.0 (x11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11
origin_req_host 指定請求方的host名稱或者ip地址
unverifiable 設置網頁是否需要驗證,默認是False,這個參數一般也不用設置。
method method是一個字符串,用來指定請求使用的方法,比如GET,POST和PUT等。

用法示範

from urllib import request, parse

url = 'http://httpbin.org/post'
headers = {
	'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
	'Host': 'httpbin.org'
}
dict = {
	'name': 'Germey'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
response = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

也可以不在request.Request中設置headers,而用下面代碼代替。

req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章