Python登录到网页并获取受会话保护的页面的内容 [英] Python login to webpage and get contents of session protected page
问题描述
我已经为这个问题搜索了一个星期. 我想实现的目标如下:
I have been googling for this problem for a week now. The thing I want to achive is the following:
将包含正确凭据的POST请求发送到URL. 保存会话(不是cookie,因为我的网站目前不使用cookie) 使用已保存的会话打开一个受会话保护的URL并获取其内容.
Send a POST request to the URL including the correct credentials. Save the session (not cookie since my website is not using cookies at the moment) With the saved session open a session protected URL and grab the contents.
我看到了很多关于Cookie的主题,但没有看到会话,我尝试了带有请求的会话,但每次都失败了.
I have seen alot of topics on this with cookies but not with sessions, I tried sessions with requests but seems to fail everytime.
推荐答案
You want to use a URL opener. Here's a sample of how I've managed to do it. If you just want a default opener, use opener=urllib.request.build_opener()
, otherwise use the custom opener. This worked when I had to log into a website and keep a session, using URL
as your URL, user
as user, password
as password, all changed as appropriate.
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
pData=urllib.parse.urlencode({"identity":user,"password":password})
req=urllib.request.Request(URL,pData.encode('utf-8'))
opener.open(req)
req=urllib.request.Request(url)
response= opener.open(req)
这篇关于Python登录到网页并获取受会话保护的页面的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!