玩蛇网提供最新Python编程技术信息以及Python资源下载!

python requests库登录网站失败求分析脚本

想写一个自动登录脚本,拿V2EX做实验。首先分析了下登录提交的表单:

需要分析登陆界面中的html取出next,once,next值,分别为input_next_value_preinput_once_valueinput_next_value_post, 然后用requests请求页面,主要代码如下:

signin_url = "http://www.v2ex.com/signin"
user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) \
AppleWebKit/537.31 (KHTML, like Gecko) \
Chrome/26.0.1410.65 Safari/537.31"
headers = {"User-Agent": user_agent}

logininfo = {"next": input_next_value_pre,
              "u": usr_name,
              "p": passwd,
              "once": input_once_value,
              "next": input_next_value_post
              }
signin_req = requests.post(signin_url,
                           data=logininfo,
                           headers=headers,
                           )

但是响应信息signin_req.content显示并没有成功登录。谁能解释一些这个是为什么呢?


怀疑是v2ex的登录表单中有两个next字段,并且值一样,这样构建post字典第二个next就被忽略,不知道该怎么解决呢?

用requests.Session()吧

刚实现了这个脚本,跟LZ的情况一样,本来登录不上,后来添加了headers内容,现在可以登录了。
主要是headers中Origin, RefererHost这3个字段。实现后代码如下:

python
#coding=utf-8 import requests from bs4 import BeautifulSoup as bs s = requests.Session() headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', 'Origin': 'http://www.v2ex.com', 'Referer': 'http://www.v2ex.com/signin', 'Host': 'www.v2ex.com', } r = s.get('http://www.v2ex.com/signin', headers=headers) soup = bs(r.content) once = soup.find('input', {'name': 'once'})['value'] login_data = {'u': '***', 'p': '***', 'once': once, 'next': '/'} s.post('http://www.v2ex.com/signin', login_data, headers=headers) f = s.get('http://www.v2ex.com/settings', headers=headers) print f.content

请问楼主我在打开f12的时候并没有出现那个Form Data是怎么回事。。

logininfo 转成json格式 看一下。你抓包的时候看一下他是什么格式。 至少我之前遇到过这类的问题。

V2EX上答案:

修改后代码:

headers = {"User-Agent": user_agent,
           "Referer": "http://www.v2ex.com/signin"}
v2ex_session = requests.Session()
signin_req = v2ex_session.post(signin_url,
                               data=logininfo,
                               headers=headers,
                               )

logininfo不用改动即可。

参考: python登录V2EX失败

玩蛇网文章,转载请注明出处和文章网址:https://www.iplaypy.com/wenda/wd20175.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年05月31日 - 11时24分21秒 发布自玩蛇网

您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容
我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules