pythonajax登录网站,的Python:使用请求登录AJAX网站

在尝试通过Python连接并登录一个Ajax网站时遇到问题,代码使用了requests.Session()进行POST登录,但获取的仍然是未登录页面。解决方案指出,需要在登录后继续使用同一会话(session)来请求登录后的页面,并检查登录数据的发送方式(可能是params、data或headers)。同时,不应使用with语句管理Session,因为这会导致会话过早结束,影响后续请求。
摘要由CSDN通过智能技术生成

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()

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.

Thanks for your help!

Anton

解决方案

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)

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.)

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).

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值