3-urllib的post請求方式


在urllib 中,要進行post請求時,需傳入相應的data值,這里通過http://www.iqianyue.com/mypost這個網站進行測試。

案例代碼如下:

 1 #post 請求
 2 import urllib.request  3 import urllib.parse  4 base_url="http://www.iqianyue.com/mypost/"
 5 data={  6     "name":"ceo@iqianyue.com",  7     "pass":"aA123456"
 8 }  9 headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE"} 10 postdata=urllib.parse.urlencode(data).encode('utf-8') 11 req=urllib.request.Request(url=base_url,headers=headers,data=postdata,method='POST') 12 response=urllib.request.urlopen(req) 13 html=response.read() 14 # html=response.read().decode('utf-8') #這里講解一下decode()是把bytes轉化解碼為了 str ,
15 # 但是寫入文本的話,是不需要解碼的,解碼了str寫不進去,
16 print(html) 17 
18 #把文件寫入G盤
19 text=open('G:/post.html',"wb") 20 text.write(html) 21 text.close()

 

 

 

注意:對於需要傳入的data 數據,需要進行urlencode編碼。postdata=urllib.parse.urlencode(data).encode('utf-8')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM