本文为「视觉爬虫开发:通过 Puppeteer 截图 + CV 定位动态元素坐标」的速查指南,帮助你快速掌握在小红书(https://www.xiaohongshu.com/)上使用 Puppeteer 结合 OpenCV 实现视频截图与评论采集的核心思路与代码示例。文章分为四大部分:功能点列表、常用代码片段、配置建议、快速测试方式,并集成爬虫代理设置,以便直接在项目中复用。
功能点列表
- 代理 IP 接入:使用爬虫代理的隧道模式,通过域名、端口、用户名、密码进行 HTTP/HTTPS 请求认证 (16yun.cn)。
- Cookie 与 User-Agent 设置:模拟真实浏览器会话,避免被反爬。
- Puppeteer 视频截图:定位视频元素并截取帧图,或全页截图后裁剪目标区域。
- 动态元素坐标获取:将 Puppeteer 截图结果导入 OpenCV,通过模板匹配定位元素坐标 。
- 评论采集:滚动法或点击“加载更多”获取评论列表,再通过 DOM 解析提取内容。
常用代码片段
1. 启动 Puppeteer 并接入爬虫代理
const puppeteer = require('puppeteer');(async () => {// 启动无头浏览器,接入亿牛云爬虫代理 www.16yun.cnconst browser = await puppeteer.launch({args: ['--no-sandbox','--disable-setuid-sandbox','--proxy-server=tcp://t.16yun.cn:31111' // 代理域名:端口 :contentReference[oaicite:3]{index=3}]});const page = await browser.newPage();// 设置代理认证(Tunnel 模式下 Puppeteer 自动支持用户名/密码)await page.authenticate({username: 'YOUR_PROXY_USER', // 亿牛云用户名 :contentReference[oaicite:4]{index=4}password: 'YOUR_PROXY_PASS' // 亿牛云密码 :contentReference[oaicite:5]{index=5}});// 设置 Cookie 与 User-Agentawait page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ...'); // 模拟浏览器 UAawait page.setCookie({name: 'sessionid',value: 'YOUR_SESSION_ID',domain: '.xiaohongshu.com'});// 跳转到小红书视频页await page.goto('https://www.xiaohongshu.com/', { waitUntil: 'networkidle2' });// 等待视频元素出现并截屏const videoHandle = await page.waitForSelector('video'); // 定位视频元素const boundingBox = await videoHandle.boundingBox();await page.screenshot({path: 'video_frame.png',clip: {x: boundingBox.x,y: boundingBox.y,width: boundingBox.width,height: boundingBox.height}}); // 截取视频区域 :contentReference[oaicite:6]{index=6}await browser.close();
})();
2. OpenCV 模板匹配定位坐标(Python)
import cv2
import numpy as np# 加载 Puppeteer 截图
screenshot = cv2.imread("video_frame.png", 0) # 灰度化
template = cv2.imread("button_template.png", 0) # 预先截图的按钮模板# 执行多尺度模板匹配 :contentReference[oaicite:7]{index=7}
res = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
top_left = max_loc
h, w = template.shape
bottom_right = (top_left[0] + w, top_left[1] + h)# 可视化结果
cv2.rectangle(screenshot, top_left, bottom_right, 255, 2)
cv2.imwrite("matched.png", screenshot)
print(f"元素坐标:{top_left}")
3. 评论列表采集(Puppeteer)
// 在原 Puppeteer 脚本中继续:
const comments = await page.evaluate(() => {// 滚动并加载更多评论window.scrollBy(0, window.innerHeight);// 假设评论项选择器为 .comment-itemreturn Array.from(document.querySelectorAll('.comment-item')).map(el => ({user: el.querySelector('.user-name')?.innerText.trim(),text: el.querySelector('.comment-text')?.innerText.trim()}));
});
console.log(comments);
配置建议
- 代理模式:推荐使用 Tunnel 模式(隧道认证),在 HTTPS 场景下更稳定 (CSDN)。
- IP 切换:业务需要多个会话时,可自定义
Proxy-Tunnel: 随机数
HTTP 头实现精确切换 (CSDN)。 - 模板准备:针对目标动态元素,截图多种分辨率模板,并在代码中以阈值筛选最佳匹配 (OpenCV документация)。
- 等待策略:结合
waitUntil: 'networkidle2'
与page.waitForSelector()
确保视频及评论加载完成。 - 错误重试:对截图、模板匹配、请求失败等步骤添加重试逻辑,提高稳定性。
快速测试方式
- 环境准备
npm install puppeteer
pip install opencv-python-headless
- 代理连通性测试
curl -x http://YOUR_PROXY_USER:YOUR_PROXY_PASS@t.16yun.cn:31111 https://httpbin.org/ip
- Puppeteer 截图验证
node capture.js
# 检查生成的 video_frame.png 是否正确截取视频区域
- OpenCV 匹配验证
python template_match.py
# 检查 matched.png 是否在目标位置画出矩形框
- 评论采集验证
在 capture.js 末尾打印comments
,确认输出的用户名与评论内容是否符合预期。
以上即为「视觉爬虫开发:通过 Puppeteer 截图 + CV 定位动态元素坐标」的速查指南,涵盖代理接入、Cookie/UA 设置、视频截图、元素定位与评论采集四大核心功能,助你快速上手并在小红书等动态站点实现可靠的视觉爬虫方案。