96SEO 2026-08-13 02:15 0
上个月接了个内部需求。要每天定时从公司用的一个项目管理网站拉取任务数据,生成报表。这个网站没有提供官方API,只能通过网页端操作。手动操作太耗时我就想写个Python脚本自动化。
一开始想得太简单:找到登录接口,POST使用者名密码。拿到Cookie接下来用这个Cookie去访问数据页面。听起来很顺对吧,结果一上手就发现,这个网站的登录流程比我想的复杂得多——有CSRF token登录后还有一次302重定向。而且Cookie的生效方法和域名都有讲究。我前后折腾了三天把requests的Session对象、CookieJar还有HTTP状态码查了个遍,才终于让脚本稳定跑起来。

如果你也遇到需要处理复杂登录鉴权的网站。特别是那些用传统表单登录、有各种安全校验的,我踩过的这些坑或许能帮你省下不少时间。
我最开始的代码长这样:
import requests
login_url = 'https://example.com/login'
data_url = 'https://example.com/api/data'
payload = {
'username': 'my_user'。'password': 'my_pass'
}
# 尝试1:直接登录
resp = requests.post
print # 输出200,好像成功了?# 尝试用这个resp的cookies去访问数据
cookies = resp.cookies
data_resp = requests.get
print # 输出403!被拒绝了,老实说,
第一个状态码给了我虚假的希望。后来仔细看data_resp.text发现返回的是登录页面的HTML——意思就是根本没登录成功,服务器把我踢回去了。老实说,
排查过程:
resp.history发现是一个空列表。说明没有重定向,不对,感觉有问题。csrfmiddlewaretoken的字段,值是一长串字符。这个token是从登录页的HTML表单里提前获取的。sessionid的Cookie。后续的POST 登录请求,会带上这个 Cookie 一起发送。而我的脚本是直接 POST,完全没理会登录页。所以主要问题不是“发送登录请求”,而是模拟一次完整的浏览器会话:
This is first and most important lesson I learned: If you need to perform a series of aunticated requests,you must use arequests.Session.
The Session object automatically manages cookies for you – it saves any cookies returned by server and adds m to subsequent requests。perfectly mimicking a browser.
import requests
# 创建会话,这是所有操作的基础
session = requests.Session
# 可以设置一个通用的请求头,更像浏览器
session.headers.update({
'User-Agent': 'Mozilla/5.0 AppleWebKit/537.36 Chrome/120.0 Safari/537.36'
})
Pain point: 很多站点会检查 User‑Agent,如果仍然使用默认 "python-requests",会直接返回 403 或验证码页。一开始就换成常见浏览器 UA 是必不可少的一步。按理说,
The majority of modern web frameworks embed a random token in login form to defend against CSRF attacks. You must first request login page,extract this token from HTML,and n include it in your POST request.
login_page_url = 'https://example.com/login'
# 第一次 GET 请求。获取页面和初始 Cookie
login_page_response = session.get
print
# 假设 token 在 name='csrfmiddlewaretoken' 的隐藏 input 中
from lxml import html
tree = html.fromstring
csrf_token = tree.xpath
if csrf_token:
csrf_token = csrf_token
print
从else来看,print
# 常见备选字段:
# csrf_token = tree.xpath ...
# csrf_token = tree.xpath
Pain point: Token 名称千差万别,需要先打开开发者工具确认隐藏字段到底叫什么再写对应 XPath/正则抓取代码。
A successful login usually returns a 302 redirect to dashboard/homepage. The Session will follow it automatically,but you still need to verify that redirect actually happened.
login_action_url = 'https://example.com/login' # 通常与 GET 同 URL
payload = {
'username': 'your_username_here','password': 'your_password_here','csrfmiddlewaretoken': csrf_token,# 可能还有其他隐藏字段,例如 `next`
}
print
login_response = session.post
print
print
print
.history` contains a 302 and final URL is not login page itself,chances are you’re logged in.The simplest way to confirm that your session is truly aunticated is to request a page that only logged‑in users can see.
profile_url = 'https://example.com/dashboard' profile_response = session.get print if profile_response.status_code == 200: if "欢迎回来" in profile_response.text or "Dashboard" in profile_response.text: print else这方面,print else的观点是,print
If this check passes,you can now freely request any protected API endpoint.
target_data_url = 'https://example.com/api/v1/tasks' data_response = session.get if data_response.status_code == 200: data = data_response.json # 假设返回 JSON print} 条记录。") else这方面,print print
The script below integrates all steps into a reusable class. Replace placeholders with your own URLs、使用者名、密码即可运行。
。import time import requests from lxml import html class WebsiteLoginFetcher: """处理带 Cookie 登录并抓取受保护数据""" def __init__: self.base_url = base_url.rstrip self.session = requests.Session self.session.headers.update({ 'User-Agent': 'Mozilla/5.0 AppleWebKit/537.36 ' ' Chrome/120.0 Safari/537.36'。'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;怎么说呢,q=0.8','Accept-Language': 'zh-CN,zh;q=0.9,en,q=0.8',}) def _get_csrf_token: """GET 登录页 → 提取 CSRF Token""" print 从try来看,resp = self.session.get resp.raise_for_status except requests.RequestException as e: print return None tree = html.fromstring # 常见字段名集合,可自行 candidates = token_vals = for name in candidates: token_vals = tree.xpath if token_vals: break if not token_vals: token_vals = tree.xpath if token_vals: token = token_vals print return token print return None def login(self,login_url,username,password,extra_form_data=None): """执行完整登陆流程""" csrf_token = self._get_csrf_token if not csrf_token: return False payload = { "username": username,"password": password,"csrfmiddlewaretoken": csrf_token,} if extra_form_data: payload.update 从try来看,resp = self.session.post( login_url,data=payload,timeout=10,allow_redirects=True # 默认已开启,可显式写明 ) except requests.RequestException as e: print return False print print print # 简单判定是否真的跳转到了非登陆页 if resp.history and login_url not in resp.url: print return True print return False def fetch_protected_data: """使用已认证 session 抓取受保护资源""" try这方面。resp = self.session.get print if resp.status_code == 200: return resp.text # 或 resp.json 再看else,print return None except requests.RequestException as e: print return Noneif name == "main": BASEURL = "https://example.com" LOGINPAGEURL = f"{BASEURL}/login" USERNAME ="yourusernamehere" PASSWORD ="yourpasswordhere" TARGETDATAURL= f"{BASEURL}/api/somedata"
fetcher = WebsiteLoginFetcher # ---------- 登录 ---------- logged_in : bool =(fetcher.login(LOGIN_PAGE_URL,USERNAME,PASSWORD)) if logged_in : print time.sleep # 防止请求过于频繁,被风控 data : str =) if data : print # 示例打印前500字符 else : print else : print
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback