的Python:使用请求登录AJAX网站 [英] Python: Login to ajax website using request
问题描述
我尝试连接一个网站,似乎是在阿贾克斯。我想要得到的HTML网页有相同的URL作为登录页面,它只是改变了,一旦你登录。 这是我的code:
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
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()
使用同一个会话,登录时,你有饼干重新发送后续请求。由于它是AJAX,您需要检查哪些额外的数据,标题或饼干正在发送时,通过浏览器(以及它是否 GET
或后完成code>来检索后续页。)
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.)
有关登录后()
登录信息可能被发为 PARAMS
公布数据
或标题
。检查哪一个是发生在你的浏览器(使用开发工具 - >网络,在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).
另外,不要使用与
上下文会话,因为它会立即结束会话,你退出了code座。你可能希望你的会话取值
来持续更长的时间不仅仅是登录,因为它是管理你的饼干等。
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屋!