新闻内容分页和懒加载的处理技术方案
解读
国内主流新闻站点(新浪、网易、腾讯、澎湃新闻等)为了 SEO 与广告曝光,普遍采用“多页分页 + 瀑布流懒加载”混合模式:
- 分页:URL 规律明显(/index_2.html、?page=3、/20230620/123456_3.shtml),但页码可能跳号或隐藏。
- 懒加载:滚动到视口才通过 JSONP/XHR 拉取后续片段,返回格式多为 JSON(含 html 字段)或纯 HTML 片段,字段名高度压缩(如“d”、“c”)。
- 反爬:请求头校验(Referer、X-Requested-With)、cookie 绑定、时间戳签名、字体加密;部分媒体在第二页开始植入 302 跳转或 JS 生成 token。
面试官想确认:
- 你是否能“先识规律,再定策略”,而不是一上来就暴力循环。
- 能否用 Beautiful Soup 精准提取“下一页”线索,同时把懒加载接口当成独立数据源,而不是死磕 Selenium。
- 遇到反爬能否给出合规、低成本的工程化方案(代理池、请求降速、缓存、UA 池),而不是一句“上 Selenium”敷衍。
知识点
-
分页 URL 的三种规律
a. 静态路径替换:/2023/0619/c123-456_#{n}.shtml
b. 查询参数:/api/newsList?page=#{n}&channel=tech
c. 哈希路由+JS:location.hash = '#/page/3',需先逆向 JS 找到真实接口。 -
懒加载接口定位
- DevTools Network 面板筛选 XHR/Fetch,按 size 倒排,通常最大包即为列表接口。
- 关键字搜索:在 Sources 全局搜 “ajax”、“loadMore”、“nextPageUrl”,可快速定位加密函数。
-
Beautiful Soup 在分页链路中的角色
- 第一页 HTML 用 Soup 提取:总页数、下一页 a 标签的 href、数据行唯一标识(data-docid)。
- 对 JSON 返回的 html 片段,仍可扔给 Soup 做二次解析,保持代码风格统一。
-
去重与断点续爬
- 用 Redis 集合存储已抓 docid,崩溃后从失败页码续跑。
- 按“页码+docid”双键去重,防止编辑手动增补旧稿导致重复。
-
反爬对抗(合法范围内)
- 请求头:UA 随机、Accept-Language 设 zh-CN,zh;q=0.9,X-Forwarded-For 设省内宽带 IP 段。
- 限速:单 IP 单站点 1.2~1.8 s 间隔,夜间高峰再降 30%。
- 字体加密:找到 woff 文件,用 fontTools 建立字形→unicode 映射表,在 Soup 提取后即时替换。
-
工程化细节
- 封装“分页迭代器”:yield 返回每页 Soup 对象,调用方无感知是静态页还是懒加载 JSON。
- 日志:记录 status_code、cost、exception,方便后期给媒体运维发邮件申诉封 IP。
答案
下面给出一套可直接落地的 Python 方案,全部基于 requests + Beautiful Soup,不依赖浏览器驱动,符合国内大多数媒体站的反爬强度。
- 入口函数:先拿第一页 HTML,提取总页数及懒加载接口模板
import requests, re, time, math
from bs4 import BeautifulSoup
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Referer": "https://news.sina.com.cn/",
}
def get_total_pages(url):
resp = requests.get(url, headers=HEADERS, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "lxml")
# 新浪新闻分页示例
page_script = soup.find("script", text=re.compile("var.*pages"))
total = 1
if page_script:
m = re.search(r"pages\s*:\s*(\d+)", page_script.string)
total = int(m.group(1)) if m else 1
return total, resp.text
- 静态分页生成器
def static_page_urls(start_url, total):
base = re.sub(r"_\d+\.s?html?$", "", start_url)
for p in range(1, total + 1):
yield f"{base}_{p}.shtml"
- 懒加载接口生成器(以网易为例)
def lazy_urls(channel, docid, total):
# 接口模板来自 JS 逆向
api = "https://3g.163.com/{}/api/article/{}/page/{}"
for p in range(2, total + 1): # 第一页已在 HTML 中
yield api.format(channel, docid, p)
- 统一解析函数
def parse_items(html_or_json):
if html_or_json.strip().startswith("{"):
import json
data = json.loads(html_or_json)
html = data["html"] if "html" in data else data["d"]
else:
html = html_or_json
soup = BeautifulSoup(html, "lxml")
for tag in soup.select("div.news-item"):
yield {
"title": tag.select_one("h3 a").get_text(strip=True),
"url": tag.select_one("h3 a")["href"],
"ptime": tag.select_one(".time").text,
}
- 主循环:先抓静态,再抓懒加载,自动降速
def crawl_list(start_url):
total, first_html = get_total_pages(start_url)
# 1) 静态页
for url in static_page_urls(start_url, total):
resp = requests.get(url, headers=HEADERS, timeout=10)
for item in parse_items(resp.text):
yield item
time.sleep(1.5)
# 2) 懒加载(若存在)
channel, docid = "tech", "ABCD1234" # 可从第一页 HTML 提取
for api in lazy_urls(channel, docid, total):
resp = requests.get(api, headers=HEADERS)
for item in parse_items(resp.text):
yield item
time.sleep(1.2)
- 去重与落地
import redis, hashlib
r = redis.Redis(decode_responses=True)
def save(item):
sig = hashlib.md5((item["url"] + item["ptime"]).encode()).hexdigest()
if r.sadd("news:sig", sig):
# 写数据库或文件
print("saved ->", item["title"])
整套代码保持 Beautiful Soup 作为解析核心,分页与懒加载仅差异在“如何拿到 HTML”,上层业务无需改动即可适配新站点。
拓展思考
- 若接口返回 GraphQL 或 protobuf,Beautiful Soup 无法直接解析,需先转 HTML 或 JSON;此时可封装“前置解码器”,保持 Soup 输入一致,实现“异构数据源同构解析”。
- 对于“滚动即加载”无总页数场景,可维护“连续空页计数器”≥3 即停,或检测返回片段长度<阈值,避免无限请求。
- 大型项目可把“分页策略”抽象为 Strategy 类:StaticStrategy、LazyJsonStrategy、GraphQLStrategy,配合工厂模式注册到 Spider,符合开闭原则。
- 国内媒体常把“评论数”、“点赞数”放在独立接口,可复用同一套限速器与重试器,做到“主内容+互动指标”一次性拉通,方便后续 NLP 情感分析。
- 合规性:遵守《反不正当竞争法》与 robots 协议,抓取频率不得影响站点正常运营;对需授权的白名单媒体,应通过官方 RSS 或内容开放平台获取,Beautiful Soup 仅作兜底清洗。