视觉爬虫开发:通过Puppeteer截图+CV定位动态元素坐标

本文为「视觉爬虫开发:通过 Puppeteer 截图 + CV 定位动态元素坐标」的速查指南,帮助你快速掌握在小红书(https://www.xiaohongshu.com/)上使用 Puppeteer 结合 OpenCV 实现视频截图与评论采集的核心思路与代码示例。文章分为四大部分:功能点列表、常用代码片段、配置建议、快速测试方式,并集成爬虫代理设置,以便直接在项目中复用。

功能点列表

  1. 代理 IP 接入:使用爬虫代理的隧道模式,通过域名、端口、用户名、密码进行 HTTP/HTTPS 请求认证 (16yun.cn)。
  2. Cookie 与 User-Agent 设置:模拟真实浏览器会话,避免被反爬。
  3. Puppeteer 视频截图:定位视频元素并截取帧图,或全页截图后裁剪目标区域。
  4. 动态元素坐标获取:将 Puppeteer 截图结果导入 OpenCV,通过模板匹配定位元素坐标 。
  5. 评论采集:滚动法或点击"加载更多"获取评论列表,再通过 DOM 解析提取内容。

常用代码片段

1. 启动 Puppeteer 并接入爬虫代理

javascript 复制代码
const puppeteer = require('puppeteer');

(async () => {
  // 启动无头浏览器,接入亿牛云爬虫代理 www.16yun.cn
  const 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-Agent
  await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ...');  // 模拟浏览器 UA
  await 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)

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)

javascript 复制代码
// 在原 Puppeteer 脚本中继续:
const comments = await page.evaluate(() => {
  // 滚动并加载更多评论
  window.scrollBy(0, window.innerHeight);
  // 假设评论项选择器为 .comment-item
  return 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() 确保视频及评论加载完成。
  • 错误重试:对截图、模板匹配、请求失败等步骤添加重试逻辑,提高稳定性。

快速测试方式

  1. 环境准备
bash 复制代码
npm install puppeteer
pip install opencv-python-headless
  1. 代理连通性测试
bash 复制代码
curl -x http://YOUR_PROXY_USER:YOUR_PROXY_PASS@t.16yun.cn:31111 https://httpbin.org/ip
  1. Puppeteer 截图验证
bash 复制代码
node capture.js
# 检查生成的 video_frame.png 是否正确截取视频区域
  1. OpenCV 匹配验证
bash 复制代码
python template_match.py
# 检查 matched.png 是否在目标位置画出矩形框
  1. 评论采集验证
    在 capture.js 末尾打印 comments,确认输出的用户名与评论内容是否符合预期。

以上即为「视觉爬虫开发:通过 Puppeteer 截图 + CV 定位动态元素坐标」的速查指南,涵盖代理接入、Cookie/UA 设置、视频截图、元素定位与评论采集四大核心功能,助你快速上手并在小红书等动态站点实现可靠的视觉爬虫方案。

相关推荐
喵手10 小时前
Python爬虫零基础入门【第九章:实战项目教学·第15节】搜索页采集:关键词队列 + 结果去重 + 反爬友好策略!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·搜索页采集·关键词队列
喵手10 小时前
Python爬虫零基础入门【第九章:实战项目教学·第14节】表格型页面采集:多列、多行、跨页(通用表格解析)!
爬虫·python·python爬虫实战·python爬虫工程化实战·python爬虫零基础入门·表格型页面采集·通用表格解析
0思必得011 小时前
[Web自动化] 爬虫之API请求
前端·爬虫·python·selenium·自动化
喵手11 小时前
Python爬虫实战:从零构建 Hacker News 数据采集系统:API vs 爬虫的技术抉择!(附CSV导出 + SQLite 存储)!
爬虫·python·爬虫实战·hacker news·python爬虫工程化实战·零基础python爬虫教学·csv导出
0思必得012 小时前
[Web自动化] 爬虫之网络请求
前端·爬虫·python·selenium·自动化·web自动化
喵手13 小时前
Python爬虫零基础入门【第九章:实战项目教学·第6节】断点续爬:任务状态表 + 失败队列重放!
爬虫·python·爬虫实战·python爬虫工程化实战·零基础python爬虫教学·断点续爬·任务状态表
安然无虞15 小时前
「深入理解多线程编程」再谈线程
爬虫·python·测试工具
小尘要自信15 小时前
高级网络爬虫实战:动态渲染、反爬对抗与分布式架构
分布式·爬虫·架构
深蓝电商API15 小时前
Selenium 与 BeautifulSoup 结合解析页面
爬虫·python·selenium·beautifulsoup
深蓝电商API17 小时前
Selenium 绕过 Cloudflare 反爬检测
爬虫·python·selenium