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

使用Python requests的session.get()无法加载整页动态数据的解决方案咨询

基于requests库的动态数据加载解决方案

1. 排查POST请求失败的核心原因

连接错误通常和请求头完整性、请求体参数、反爬机制直接相关,按以下步骤逐一验证:

  • 补全完整请求头:从浏览器开发者工具的Network面板中复制滚动加载时的全部请求头,包括Cookie(如果网站依赖会话验证)、完整的Sec-Ch-Ua系列字段,不要省略任何内容。很多网站会通过缺失的请求头字段识别非浏览器请求。
  • 还原请求体结构:Content-Length变化是因为请求体内容不同,滚动加载的请求体里必然包含分页参数(如page、offset、limit)、最后一条数据的标识(如last_id)或时间戳。找到对应POST请求的Payload/Request Body,复制完整JSON结构,替换分页参数即可请求更多数据。
  • 处理SSL与跨域问题:如果是HTTPS连接错误,可临时关闭SSL验证测试(生产环境不建议):requests.post(url, verify=False);同时确保Origin和Referer头的域名与实际请求完全一致,避免拼写错误。

2. 模拟滚动加载的分页请求逻辑

拿到正确的请求头和请求体后,通过循环请求分页数据:

import requests
import json
import time

session = requests.Session()
# 先访问初始页面,获取必要的会话Cookie或初始化参数
initial_url = "你的目标页面URL"
session.get(initial_url)

# 从浏览器复制的完整请求头
headers = {
    "Accept": "application/json, text/plain, */*",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "en;q=0.9",
    "Content-Type": "application/json",
    "Origin": "原网站域名",
    "Referer": "原网站页面URL",
    "Sec-Ch-Ua": "\"Not_A Brand\";v=\"8\", \"Chromium\";v=\"120\", \"Google Chrome\";v=\"120\"",
    "Sec-Ch-Ua-Mobile": "?0",
    "Sec-Ch-Ua-Platform": "\"Windows\"",
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "cross-site",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Cookie": "从浏览器复制的完整Cookie字符串"
}

# 初始请求体(从浏览器复制的第一个滚动请求Payload)
payload = {
    "limit": 5,
    "offset": 0,
    # 补充实际存在的参数,如last_item_id、timestamp等
}

collect_url = "https://url/v1/collect"
all_data = []

try:
    while True:
        response = session.post(collect_url, headers=headers, data=json.dumps(payload))
        if response.status_code != 200:
            print(f"请求失败,状态码:{response.status_code}")
            break
        data = response.json()
        current_list = data.get("list", [])
        if not current_list:
            # 无更多数据,终止循环
            break
        all_data.extend(current_list)
        # 更新分页参数,根据实际逻辑调整(示例为offset递增)
        payload["offset"] += 5
        # 若依赖最后一条数据ID,则改为:payload["last_id"] = current_list[-1]["id"]
        time.sleep(1)  # 添加请求间隔,避免触发反爬

except requests.exceptions.RequestException as e:
    print(f"连接错误:{str(e)}")

print(f"共获取到{len(all_data)}条数据")

3. 修复requests_html无效的问题

requests_html的render()默认仅渲染初始页面,不会触发滚动事件,可通过执行JS代码模拟滚动:

from requests_html import HTMLSession
import time

session = HTMLSession()
r = session.get(initial_url)
# 多次模拟滚动到底部,触发加载逻辑
for _ in range(3):
    r.html.render(scrolldown=1, sleep=1)
# 提取目标数据
items = r.html.find("列表元素的CSS选择器")
print(f"获取到{len(items)}条数据")

此方法稳定性不如直接调用API,优先推荐第一种方案。

4. 反爬应对补充技巧

  • 控制请求频率:每次请求后添加1-2秒间隔,避免高频请求被封禁。
  • 动态更新Cookie:若Cookie存在过期时间,定期重新请求初始页面更新会话。
  • 使用代理IP:出现403或连接拒绝时,切换代理IP继续请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 05:21:11