You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Requests库登录网站失败,寻求排查解决方案

网站登录爬取问题

问题背景

需要爬取某网站信息,但只能使用Firefox 47版本,而Selenium不支持该版本,因此决定采用Requests库结合BeautifulSoup实现。目前第一步的网站登录始终无法成功。

已尝试操作

  • 通过Firefox开发者工具获取请求头、Cookie和表单数据,并据此创建会话发送请求。

相关代码

import requests


login_url = "https://ip.adress/website/session/login.php"
protected_url = "https://ip.adress/website/#dashboard/overview/overview"


cookies = {
    'sess': '4rk02yn7r1l3pn0bkj4zk',
    'PHPSESSID': 'ogtkif390qrhur8b3krm4anf53',
}

headers = {
    'Host': 'ip.adress',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'fr-FR,fr;q=0.8,en-US;q=0.5,en;q=0.3',
    'Accept-Encoding': 'gzip, deflate, br',
    'Referer': 'https://ip.adress/website/session/login.php',
    # 'Cookie': 'sess=4rk02yn7r1l3pn0bkj4zk; PHPSESSID=ogtkif390qrhur8b3krm4anf53',
    'Connection': 'keep-alive',
}

data = {
    'embed': '',
    'bookmark_string': '',
    'user': 'username',
    'passu': 'password',
    'pass': 'random string which depends on the passu value',
}


with requests.Session() as s:
    r1 = s.get(login_url, verify=False)
    r2 = s.post(login_url, cookies=cookies, headers=headers, data=data, verify=False)
    r3 = s.get(protected_url, verify=False)

    print(r3.text)

问题现象

  • 执行print(r3.text)返回的是登录页的HTML内容
  • print(r3.history)显示请求过程中存在302重定向响应

登录页面表单结构

<form name="f_login" id="f_login" method="POST" action="login.php">
                    <input type="hidden" name="embed" value=""/>
                    <input type="hidden" name="bookmark_string" id="bookmark_string" value=""/>
....
....
<input type="text" size='25' maxlength="64" id='user' name="user" value="" />

<input type="password" onfocus="$('#wup').hide(); $('#nt_1').hide(); $('#nt_pass').hide();" id="passu" size='25' name="passu" autocomplete="off"/>
<input type="hidden" id="pass" name="pass"/>

</form>

补充信息:r2响应头

header_2 = {'Date': 'Mon, 19 Dec 2022 16:09:58 GMT', 'Server': 'Apache',
            'X-Frame-Options': 'SAMEORIGIN',
            'Strict-Transport-Security': 'max-age=63072000; includeSubdomains; preload',
            'X-XSS-Protection': '1; mode=block',
            'Vary': 'User-Agent,Accept-Encoding',
            'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT',
            'Cache-Control': 'no-store, no-cache, must-revalidate',
            'Pragma': 'no-cache',
            'Content-Encoding': 'gzip',
            'Content-Length': '2946', 'Keep-Alive': 'timeout=5, max=97',
            'Connection': 'Keep-Alive',
            'Content-Type': 'text/html; charset=UTF-8',
            }

内容的提问来源于stack exchange,提问作者bevilex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:45:39