首页 > python使用requests的post请求模拟饭否登录,得到的响应为何和浏览器不一致?

python使用requests的post请求模拟饭否登录,得到的响应为何和浏览器不一致?

想尝试登录饭否,post请求以后,返回响应res直接就是get的内容了,并不是浏览器里post后的response。
用chrome查看到post以后,status code是302,response headers如下:


然后下一步才是到http://fanfou.com/home


而在python里用requests的post请求,直接就返回status code 200了,response headers的信息和上面是一样的(图如下),那那个status code 302的响应上哪去了呢?


如果这样的话,我就没办法获得登录的cookies了。
源码如下:

import requests
from bs4 import BeautifulSoup

url = 'http://fanfou.com/login?fr=%2Flogin'
#url_l = 'http://fanfou.com/login'

s = requests.session()
r = s.get(url)
action = BeautifulSoup(r.content, "lxml").find('input', attrs={'name':'action'})['value']
token = BeautifulSoup(r.content, "lxml").find('input', attrs={'name':'token'})['value']
urlfrom = BeautifulSoup(r.content, "lxml").find('input', attrs={'name':'urlfrom'})['value']

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'Accept-Encoding':'gzip, deflate',
    'Accept-Language':'zh-CN,zh;q=0.8,en;q=0.6',
    'Cache-Control':'max-age=0',
    'Content-Length':'163',
    'Content-Type':'application/x-www-form-urlencoded',
    'DNT':'1',
    'Host':'fanfou.com',
    'Origin':'http://fanfou.com',
    'Proxy-Connection':'keep-alive',
    'Referer':'http://fanfou.com/login?fr=%2F',
    'Upgrade-Insecure-Requests':'1',
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36'
    }

login_data = {
    'loginname':'*************@*********',
    'loginpass':'************',
    'action':action,
    'token':token,
    'urlfrom':urlfrom
        }

res = requests.post(url, data=login_data, headers=headers, cookies=r.cookies)
print res.status_code
print res.headers

我之前也遇到过这种情况,应该是requests自动处理了这个重定向,用requests库登录的话,可以用它的session来保存会话状态,cookies就一直保存着,不用手动去维护了.

s = requests.Session()
s.post(....)
s.get(....)

requests会自动处理重定向,这个还是很有用的, 因为它在重定向的时候,把cookie也给你保存了,在模拟登录成功之后的后续操作,就很方便了。但是如果是urllib2的话, 重定向默认会丢失cookie

【热门文章】
【热门文章】