|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 和vvv 于 2017-6-22 11:59 编辑
19 自动模拟HTTP请求之自动POST实战
post请求最常用的地方是登录,即表单的提交。- import urllib.request
- import urllib.parse
- #表单提交
- #数据以字典形式组织,并设置编码
- postdata = urllib.parse.urlencode({
- "name":"Python",
- "passwd":"123456"
- }).encode("utf-8")
- #使用urllib.request.Request(真实post地址,post数据)进行post
- req = urllib.request.Request("http://httpbin.org/post",postdata)
- #访问
- rst = urllib.request.urlopen(req).read().decode("utf-8")
- print(rst)
复制代码 结果:- {
- "args": {},
- "data": "",
- "files": {},
- "form": {
- "name": "Python",
- "passwd": "123456"
- },
- "headers": {
- "Accept-Encoding": "identity",
- "Connection": "close",
- "Content-Length": "25",
- "Content-Type": "application/x-www-form-urlencoded",
- "Host": "httpbin.org",
- "User-Agent": "Python-urllib/3.6"
- },
- "json": null,
- "origin": "222.179.24.106",
- "url": "http://httpbin.org/post"
- }
复制代码 可以发现,我们post过去的数据形成了一个表单。再试一下:- import urllib.request
- import urllib.parse
- #表单提交
- posturl = "http://www.baidu.com"
- #数据以字典形式组织,并设置编码
- postdata = urllib.parse.urlencode({
- "name":"Python",
- "passwd":"123456",
- "性别":"男",
- "出生地":"中国"
- }).encode("utf-8")
- #使用urllib.request.Request(真实post地址,post数据)进行post
- req = urllib.request.Request("http://httpbin.org/post",postdata)
- #访问
- rst = urllib.request.urlopen(req).read().decode("utf-8")
- print(rst)
复制代码 结果:{
"args": {},
"data": "",
"files": {},
"form": {
"name": "Python",
"passwd": "123456",
"\u51fa\u751f\u5730": "\u4e2d\u56fd",
"\u6027\u522b": "\u7537"
},
"headers": {
"Accept-Encoding": "identity",
"Connection": "close",
"Content-Length": "101",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "Python-urllib/3.6"
},
"json": null,
"origin": "222.179.23.244",
"url": "http://httpbin.org/post"
}
提交的数据也是形成了表单,其中的中文经过了unicode转码。
总的来说,在爬虫里,post请求主要是用来自动模拟登陆,然后爬取更深层次的页面。
|
评分
-
查看全部评分
|