urllib.request子產品的用法
urlopen
urllib.request.urlopen(url),括号内可傳遞的參數除了url,還有timeout, cafile,capath,context。
下面詳細介紹各參數
data:如果是位元組流編碼格式的内容,需要用bytes()方法進行轉化,
當傳遞這個參數後,請求方式就不再是GET,而是POST。bytes(str,encoding=‘utf8’),bytes的第一個參數是字元串,如果是字典, 需要使用*urllib.parse.urlencode()*方法來将字典轉化為字元串,第二個參數是編碼格式。
timeout:設定逾時時間,機關是s。
cafile:CA憑證
capath:CA憑證路徑
context:必須是SSLContext類型,用來指定ssl設定。
代碼如下:
import urllib.parse
import urllib.request
url = 'http://httpbin.org/post'
# 對參數data進行格式轉化
data = bytes(urllib.parse.urlencode({'word':'hello'}), encoding='utf8')
# urlopen 可傳遞的參數除了url 還有timout等其他參數
response = urllib.request.urlopen(url, data=data, timeout=100,capath=None,cafile=None,context=None,cadefault=False)
print(response.read())
Request的用法
urlopen()方法可以實作最基本請求的發起,如果請求中需要加入Header等資訊可以利用強大的Request類來建構。
Request的參數:url,data,header,origin_req_host, unverifable, method.
oringin_req_host: 請求方的host名稱或IP
univerfable: 表示這個請求是不是無法驗證的。預設為False,即有足夠的請求權限。
method: 是一個字元串,表示請求方法,即GET,POST,PUT.
代碼如下:
import urllib.request
import urllib.parse
url = 'http://httpbin.org/post'
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
'host': 'httpbin.org',
}
dict={
'name':'Germey'
}
data = bytes(urllib.parse.urlencode(dict),encoding='utf8')
equest = urllib.request.Request(url,data=data, headers=headers, method='POST')
# 發起請求并擷取請求結果
res = urllib.request.urlopen(request)
print(res.read().decode('utf-8'))
以上就是本篇文章的所有内容