說明:urllib發送http請求並不是很人性化,更推薦使用在urllib基礎上封裝的、python2和python3都兼容的requests模塊,移步查看。
一、get請求
get請求就是在構造Request對象時,只傳入url參數
更多的教程發送get請求的寫法直接是不構造Request對象而直接urllib.request.urlopen(url),但為了與后邊post和header的統一推薦還是構造Request。
import urllib.request url_request="http://10.10.6.92/Pages/login.htm"
request_obj=urllib.request.Request(url=url_request) response_obj=urllib.request.urlopen(request_obj) html_code=response_obj.read().decode('utf-8') print(html_code)
二、post請求
post請求與get的區別,是在構造Request對象時除了傳入url參數還要傳入data參數
不用懷疑,真的加上data,發送數據時就自動由get方法改為post方法
當然其實也可以在構造Request時多傳入method參數(比如method='POST'),強制使用某種方法;
不過注意這里的method參數只是生硬地用該參數的值去替換請求動詞(比如你設為‘XX’,請求動詞就是‘XX’),其他東西不會變的(比如有post_data強傳‘GET’,數據還是用POST的形式提交)。
import urllib.request url_request="http://10.10.6.92/Pages/login.htm" post_data='<?xml version="1.0" encoding="utf-8" ?><request version="1.0" systemType="NVMS-9000" clientType="WEB"><content><userName><![CDATA[admin]]></userName><password>MTIzNDU2</password></content></request>' post_data=post_data.encode('utf-8') request_obj=urllib.request.Request(url=url_request,data=post_data) response_obj=urllib.request.urlopen(request_obj) html_code=response_obj.read().decode('utf-8') print(html_code)
三、使用代理
使用代理的關鍵是下邊中間的四行代碼
同樣強調使用代理和是get方法,還是post方法,還是使用代理都沒有關聯
import urllib.request
url_request="http://10.10.6.92/Pages/login.htm"
request_obj=urllib.request.Request(url=url_request)
request_obj.set_proxy('127.0.0.1:8080','http')
response_obj=urllib.request.urlopen(request_obj)
html_code=response_obj.read().decode('utf-8')
print(html_code)
python默認發送頭部如下,這四個值和自定義頭部類似於父類和子類的關系:
四、自定義header
自定義header,就是在構造Request對象時多傳入headers參數
header與是get方法還是post方法是沒有關聯的;也就是說post方法想自定義頭部,那么在post的基礎方多傳入headers參數即可
import urllib.request url_request="http://10.10.6.92/Pages/login.htm" header_selfdefine={ 'Host':'10.10.6.92', 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:59.0) Gecko/20100101 Firefox/59.0', 'Accept': '*/*', 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2', 'Accept-Encoding': 'gzip, deflate', 'Referer': 'http://10.10.6.92/Pages/login.htm' } request_obj=urllib.request.Request(url=url_request,headers=header_selfdefine) response_obj=urllib.request.urlopen(request_obj) html_code=response_obj.read().decode('utf-8') print(html_code)
五、自定義Cookie
如果使用add_header添加的請求頭在header中已經存在,那么header中同一請求頭的值將被覆蓋;或者叫以add_header的為准。
import urllib.request url_request = 'http://10.10.6.92/Pages/login.htm' request_obj = urllib.request.Request(url=url_request) request_obj.add_header('Cookie','username="root", password="toor"') response_obj = urllib.request.urlopen(request_obj) html_code = response_obj.read().decode('utf-8') print(html_code)