鱼C论坛

 找回密码
 立即注册
查看: 2635|回复: 0

[技术交流] 19 自动模拟HTTP请求之自动POST实战

[复制链接]
发表于 2017-6-22 11:08:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 和vvv 于 2017-6-22 11:59 编辑
19 自动模拟HTTP请求之自动POST实战

post请求最常用的地方是登录,即表单的提交。
  1. import urllib.request
  2. import urllib.parse
  3. #表单提交
  4. #数据以字典形式组织,并设置编码
  5. postdata = urllib.parse.urlencode({
  6.     "name":"Python",
  7.     "passwd":"123456"
  8. }).encode("utf-8")
  9. #使用urllib.request.Request(真实post地址,post数据)进行post
  10. req = urllib.request.Request("http://httpbin.org/post",postdata)
  11. #访问
  12. rst = urllib.request.urlopen(req).read().decode("utf-8")
  13. print(rst)
复制代码
结果:
  1. {
  2.   "args": {},
  3.   "data": "",
  4.   "files": {},
  5.   "form": {
  6.     "name": "Python",
  7.     "passwd": "123456"
  8.   },
  9.   "headers": {
  10.     "Accept-Encoding": "identity",
  11.     "Connection": "close",
  12.     "Content-Length": "25",
  13.     "Content-Type": "application/x-www-form-urlencoded",
  14.     "Host": "httpbin.org",
  15.     "User-Agent": "Python-urllib/3.6"
  16.   },
  17.   "json": null,
  18.   "origin": "222.179.24.106",
  19.   "url": "http://httpbin.org/post"
  20. }
复制代码
可以发现,我们post过去的数据形成了一个表单。再试一下:
  1. import urllib.request
  2. import urllib.parse
  3. #表单提交
  4. posturl = "http://www.baidu.com"
  5. #数据以字典形式组织,并设置编码
  6. postdata = urllib.parse.urlencode({
  7.     "name":"Python",
  8.     "passwd":"123456",
  9.     "性别":"男",
  10.     "出生地":"中国"
  11. }).encode("utf-8")
  12. #使用urllib.request.Request(真实post地址,post数据)进行post
  13. req = urllib.request.Request("http://httpbin.org/post",postdata)
  14. #访问
  15. rst = urllib.request.urlopen(req).read().decode("utf-8")
  16. 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请求主要是用来自动模拟登陆,然后爬取更深层次的页面。




评分

参与人数 4荣誉 +6 鱼币 +17 贡献 +2 收起 理由
熊孩子的爱 + 1 + 1 支持楼主!
Undo + 5 + 5 + 2
不二如是 + 5 支持楼主!
小甲鱼 + 6 支持楼主!

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-20 04:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表