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