Python:使用请求登录ajax网站 [英] Python: Login to ajax website using request

查看:26
本文介绍了Python:使用请求登录ajax网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试连接一个似乎在 Ajax 中的网站.我想要获取的 html 页面与登录页面具有相同的 URL,它只会在您登录后更改.这是我的代码:

I am trying to connect a website which seems to be in Ajax. The html page I want to get has the same URL as the landing page, it just changes once you login. Here's my code :

URL = 'http://www.pogdesign.co.uk/cat/'
payload = {' password': 'password', ' sub_login': 'Account Login', 'username': 'email'}

with requests.Session() as s:
    s.post(URL, data=payload)
    sock = urllib.urlopen(URL)
    psource = sock.read()

我得到的页面是未登录页面".我怀疑我可能忘记了有关标题的某些内容,或者这根本不是 ajax 的工作方式.

The page I get is the "not logged in page". I suspect I might have forgotten something about headers, or this is simply not how ajax works.

感谢您的帮助!

安东

推荐答案

您正在使用 session.post 发布登录信息,但随后尝试使用 urllib.urllib 没有关于您的登录数据的任何信息(例如会话 cookie),除非您明确提供.当您发布时,您并没有捕捉到响应.即使您不需要它,请继续使用会话再次请求登录页面.

You're posting your login with session.post but then trying to read the logged in page with urllib. urllib doesn't have any information about your login data (session cookie, for example), unless you explicitly provide it. When you post, you're not capturing the response. Even if you didn't require it, continue to use the session to request the login page again.

response = s.post(URL, data=payload)
# response holds the HTTP status, cookie data and possibly the "logged in page" html.
# check `response.text` if that's the case. if it's only the authentication cookie...
logged_in_page = s.get(URL)

当您使用同一个会话执行 s.get() 时,您在登录时获得的 cookie 将重新发送以供后续请求使用.由于它是 AJAX,因此您需要检查通过浏览器发送的附加数据、标头或 cookie(以及是 get 还是 post 以检索后续页面.)

When you do s.get() using the same session, the cookies you got when logging in are re-sent for subsequent requests. Since it's AJAX, you need to check what additional data, headers or cookies are being sent when done via browser (and whether it's get or post to retrieve subsequent pages.)

对于登录post(),登录数据可以作为params、posted dataheaders 发送.检查您的浏览器中发生了哪一个(使用开发工具 --> Firefox 或 Chrome 中的网络").

For the login post() login data may be sent as params, posted data or headers. Check which one is happening in your browser (using the dev tools --> "Network" in Firefox or Chrome).

另外,不要在会话中使用 with 上下文,因为它会在您退出该代码块后立即结束会话.您可能希望会话 s 的持续时间不仅仅是登录,因为它正在管理您的 cookie 等.

Also, don't use the with context with sessions because it will end the session as soon as you exit that code block. You probably want your session s to last longer than just logging in, since it's managing your cookies, etc.

这篇关于Python:使用请求登录ajax网站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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