python - 使用 requests 登录后获取受限页面,urllib2 python

标签 python python-2.7 python-requests

我正在尝试登录 this使用 python-requests 的页面

headers = {
    'content-type': 'application/x-www-form-urlencoded',
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36'
}

data = {
    'username':myusername,
    'password':mypassword,
}
r = requests.post(url,data=data,headers=headers)

我尝试通过 print r 打印返回的响应 输出为<Response [200]>但 html 页面是登录页面,但我期待登录后我们将被重定向到的其他页面的 html。

最佳答案

登录表单包含几个隐藏字段:

<input type="hidden" name="lt" value="LT-1314930-GPfgUfyUj5eRY4RCaoa1Xi3gi5Jfsf" />
<input type="hidden" name="execution" value="e3s1" />
<input type="hidden" name="_eventId" value="submit" /> 

很可能第一个字段(也许第二个字段)是自动生成的并与 session 相关联。您需要首先加载登录页面(使用 session ),解析这些字段并将它们包含在您的 POST 中。

您收到 200 条回复的原因是该网站将未经授权的请求重定向回登录页面;检查r.history,该列表中将会有一个或多个 302 响应。

您可以使用 BeautifulSoup 来解析它,或者使用 robobrowser ,它结合了 requests 和 BeautifulSoup,以及专用的表单处理程序,以创建一个类似浏览器的框架来导航网站:

from robobrowser import RoboBrowser

browser = RoboBrowser(history=True,
    user_agent='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/33.0.1750.152 Chrome/33.0.1750.152 Safari/537.36')
browser.open('http://selleraccounts.snapdeal.com/')

form = browser.get_form(id='fm1')
form['username'].value = myusername
form['password'].value = mypassword
browser.submit_form(form)

关于python - 使用 requests 登录后获取受限页面,urllib2 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23720379/

相关文章:

python - Django mongonaut : 'You do not have permissions to access this content.'

python - 在python中测量多种语言文本之间的相似性的最佳方法是什么?

python - 安装 Google Cloud SDK 时出错

python - 从 python 使用 RotatingFileHandler 时无法获取备份日志文件

python - 谷歌的速率限制是多少

python-3.x - 我如何从线程中的每个请求中获取新 ip?

python - 将图像从 Flask 的 request.files 属性加载到 PIL Image

python - cython中不同字符串的相同内存地址

Python 生成错误 : failed to build modules _ssl and _hashlib

python - 使用 python 在 Elasticsearch 中进行身份验证