Python:如何登录页面并在浏览器中查看结果页面? [英] Python: How do you login to a page and view the resulting page in a browser?

查看:134
本文介绍了Python:如何登录页面并在浏览器中查看结果页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Google上搜索了很长时间了,似乎无法解决这个问题.我的很多搜索都使我发现了类似的问题,但它们似乎都与抓取/存储Cookie有关.我想我已经正确设置了,但是当我尝试打开隐藏"页面时,它一直使我回到登录页面,说我的会话已过期.

I've been googling around for quite some time now and can't seem to get this to work. A lot of my searches have pointed me to finding similar problems but they all seem to be related to cookie grabbing/storing. I think I've set that up properly, but when I try to open the 'hidden' page, it keeps bringing me back to the login page saying my session has expired.

import urllib, urllib2, cookielib, webbrowser

username = 'userhere'
password = 'passwordhere'
url = 'http://example.com'
webbrowser.open(url, new=1, autoraise=1)
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
login_data = urllib.urlencode({'username' : username, 'j_password' : password})
opener.open('http://example.com', login_data)
resp = opener.open('http://example.com/afterlogin')
print resp
webbrowser.open(url, new=1, autoraise=1)

推荐答案

首先,在进行基于cookie的身份验证时,您需要具有

First off, when doing cookie-based authentication, you need to have a CookieJar to store your cookies in, much in the same way that your browser stores its cookies a place where it can find them again.

通过python打开登录页面并成功登录后保存cookie后,应使用 MozillaCookieJar 将python创建的cookie传递为firefox浏览器可以解析的格式. Firefox 3.x不再使用MozillaCookieJar生成的cookie格式,而且我找不到可行的替代方法.

After opening a login-page through python, and saving the cookie from a successful login, you should use the MozillaCookieJar to pass the python created cookies to a format a firefox browser can parse. Firefox 3.x no longer uses the cookie format that MozillaCookieJar produces, and I have not been able to find viable alternatives.

如果您需要做的就是检索特定的(事先已知的格式格式化的)数据,那么我建议您将所有HTTP交互作用都保留在python中.这要容易得多,而且您不必依赖可用的特定浏览器.如果绝对有必要在浏览器中显示内容,则可以通过urllib2(顺便与cookielib很好地集成)呈现所谓的隐藏"页面,将html保存到临时文件并将其传递给 webbrowser.open ,这将随后呈现该特定页面.无法进行进一步的重定向.

If all you need to do is to retrieve specific (in advance known format formatted) data, then I suggest you keep all your HTTP interactions within python. It is much easier, and you don't have to rely on specific browsers being available. If it is absolutely necessary to show stuff in a browser, you could render the so-called 'hidden' page through urllib2 (which incidentally integrates very nicely with cookielib), save the html to a temporary file and pass this to the webbrowser.open which will then render that specific page. Further redirects are not possible.

这篇关于Python:如何登录页面并在浏览器中查看结果页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆