Python请求重定向登录 [英] Python requests login with redirection
问题描述
这是一个我要使用python登录的网站 http://pro.wialon.com/请求模块.登录和传递是演示.
Here is a site http://pro.wialon.com/ where I want to login with python requests module. Login and pass are demo.
import requests
with requests.Session()as c:
url = 'http://pro.wialon.com/'
payload = dict(user='demo',
passw='demo',
login_action='login')
r = c.post(url, data=payload, allow_redirects=True)
print(r.text)
坦率地说,我想获得报告(在报告"选项卡上)作为响应.但是我不知道如何登录.
Frankly, I want to get report (at the report tab) as response. But I cant figure out how to log in.
推荐答案
发布网址不正确,并且您缺少表单数据,还需要执行初始请求,发布到正确的网址,然后获取http://pro.wialon.com/service.html
:
The post url is incorrect and you are missing form data, you need to also do an initial request, post to the correct url and then get http://pro.wialon.com/service.html
:
data = {"user": "demo",
"passw": "demo",
"submit": "Enter",
"lang": "en",
"action": "login"}
head = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
with requests.Session() as c:
c.get('http://pro.wialon.com/')
url = 'http://pro.wialon.com/login_action.html'
c.post(url, data=data, headers=head)
print(c.get("http://pro.wialon.com/service.html").content)
您可以在网络标签下的chrome开发工具中查看该帖子:
You can see the post in chrome dev tools under the network tab:
发布或获取请求的默认设置是允许重定向,因此您无需在此处指定.
Also the default for post or get requests is to allow redirects so you don't need to specify it here.
您可以在登录页面源代码中看到表单操作:
You can see in the login page source, the form action:
<form class="login_bg_form" id="login_form" action="login_action.html" method="POST">
使用 bs4 :
import requests
from bs4 import BeautifulSoup
from urlparse import urljoin
data = {"user": "demo",
"passw": "demo",
"submit": "Enter",
"lang": "en",
"action": "login"}
head = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
with requests.Session()as c:
soup = BeautifulSoup(c.get('http://pro.wialon.com/').content)
redir = soup.select_one("#login_form")["action"]
url = 'http://pro.wialon.com/login_action.html'
c.post(url, data=data, headers=head)
print(c.get(urljoin("http://pro.wialon.com/", redir)).content)
现在唯一的问题是,大多数数据是使用ajax请求填充的,因此,如果要抓取数据,则需要模仿请求.
The only problem now is the data is mostly populated using ajax requests so if you want to scrape data you will need to mimic the requests.
这篇关于Python请求重定向登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!