Heim > Fragen und Antworten > Hauptteil
想写一个自动登录脚本,拿V2EX做实验。首先分析了下登录提交的表单:
需要分析登陆界面中的html取出next,once,next值,分别为input_next_value_pre
、input_once_value
、input_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就被忽略,不知道该怎么解决呢?
大家讲道理2017-04-17 11:34:37
V2EX上答案:
可能是cookie的问题,在post之前,先GET一次,把cookie存下来,再post,或者用requests的Session。
另外POST的Referer要带上。
修改后代码:
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失败
迷茫2017-04-17 11:34:37
刚实现了这个脚本,跟LZ的情况一样,本来登录不上,后来添加了headers内容,现在可以登录了。
主要是headers中Origin
, Referer
和Host
这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