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')

posted @ 2018-08-23 13:44  北鼻coder  阅读(5963)  评论(0编辑  收藏  举报