如何处理网站上的动态加载或AJAX分页?

JANSON

在抓取网页数据时,经常会遇到数据量大好几页的现象,传统的页面刷新方式已经无法满足用户体验的需求了,AJAX的分页技术很好的解决了这个问题,Ajax是一种浏览器与服务器之间的异步通信方式,是一种用于创建快速动态网页的技术,在不重新加载整个网页的情况下可以实现对网页的某部分进行更新。
由Ajax加载的页面无法直接获得对应的href链接,那么我们如何处理网站上的动态加载或AJAX分页呢?
下面来讲一下步骤:
首先,按F12打开开发者工具,找到XHR标签,点击左侧的文件,切换到 Response选项,分析request请求的URL,看是post还是get方法,观察请求返回的内容是不是我们需要的,寻找与下一页相关的信息。
其次,构造网址发送请求,利用headers下的信息构造网页,发送请求。通过返回的请求分析请求参数和响应数据,构造参数字典。
部分核心代码示例:

Python Copy
import requests

# --- The information obtained from the first step analysis. ---
api_url = "https://api.example.com/v2/articles" # The URL of the target API

# 1. Construct the request header using the information under headers.
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...",
    "X-Requested-With": "XMLHttpRequest", # Many AJAX requests will include this header.
    "Referer": "https://www.example.com/articles" # Inform the server of the request source.
}

# 2. Construct a parameter dictionary by analyzing the request parameters and response data.
params_for_next_page = {
    "limit": 20,
    "cursor": "abcdefg12345" # This value is dynamically changing.
}

最后,通过模拟请求返回获取到的数据,解析响应,保存数据为JSON格式。

Update Time:Feb 04, 2026

Comments

Tips: Support some markdown syntax: **bold**, [bold](xxxxxxxxx), `code`, - list, > reference