如何请求.会话()。如果网站不允许我登录,请获取?

2024-10-03 17:25:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试完成一个网页,需要先登录的网页垃圾。我相当肯定我有我的代码和输入名称('登录'和'密码')正确,但它仍然给我一个'登录失败'页。这是我的密码:

payload = {'login': 'MY_USERNAME', 'password': 'MY_PASSWORD'}
login_url = "https://www.spatialgroup.com.au/property_daily/"

with requests.Session() as session:

    session.post(login_url, data=payload)
    response = session.get("https://www.spatialgroup.com.au/cgi-bin/login.cgi")
    html = response.text

print(html)

我四处打探了一下,发现当我运行我的服务器时,会话不会保持登录状态会话.get(“登录页面”)。例如,如果我完成了登录过程,然后在地址栏中输入一个URL,我知道这是一个只有登录后才能访问的页面,它会将我返回到“登录失败”页面。如果我的登录会话没有被维护,我将如何解决这个问题?你知道吗


Tags: httpscomurl网页密码getresponsesession
2条回答

正如其他人所提到的,如果不知道您试图登录的实际站点,在这里很难提供帮助。你知道吗

我要指出的是,您根本没有使用任何设置的HTTP头,这是一种常见的网页登录验证检查。如果您确定以正确的格式发布数据(form-encoded与json-encoded),那么我将打开Chrome检查器并从浏览器中复制用户代理。你知道吗

s = requests.Session()
s.headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
    'Accept': '*/*'
}

另外,使用try/except模式检查每个web请求的响应状态代码也是一种很好的做法。这将帮助您在编写和测试请求时捕捉错误,而不是盲目地猜测哪些请求是错误的。你知道吗

r = requests.get('http://mypage.com')
try:
    r.raise_for_status()
except requests.exceptions.HTTPError:
    print('oops bad status code {} on request!'.format(r.status_code))

编辑:现在您已经给了我们这个站点,检查一次登录尝试会发现表单数据实际上并没有发布到那个网站,而是被发送到一个CGI脚本url。你知道吗

要找到这个,打开ChromeInspector并在您尝试登录时查看“网络”选项卡。您将看到登录名实际上被发送到https://www.spatialgroup.com.au/cgi-bin/login.cgi,而不是实际的登录页。当您提交到此登录页时,它会在登录后执行302重定向。我们可以在执行请求后检查位置,以查看登录是否成功。你知道吗

知道这一点,我会发出这样的请求:

s = requests.Session()

# try to login
r = s.post(
    url='https://www.spatialgroup.com.au/cgi-bin/login.cgi',
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3'
    },
    data={
        'login': USERNAME,
        'password': PASSWORD
    }
)

# now lets check to make sure we didnt get 4XX or 5XX errors
try:
    r.raise_for_status()
except requests.exceptions.HTTPError:
    print('oops bad status code {} on request!'.format(r.status_code))
else:
    print('our login redirected to: {}'.format(r.url))

# subsequently if the login was successful, you can now make a request to the login-protected page at this point

如果没有你正在使用的实际网站,帮助你是非常困难的。尽管如此,我还是建议你改变这一行:

session.post(login_url, data=payload)

对于这个:

session.post(login_url, json=payload)

希望这有帮助

相关问题 更多 >