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

如何使用Puppeteer获取正确的选择器?

如何使用Puppeteer获取正确的选择器?

嘿,我来帮你搞定这个问题!先把你提供的HTML结构贴出来,方便咱们对照着分析:

<div class="list-row">
    <div class="list-item">
        <div class="imgframe">
            <div class="img-wrap">
                <div class="img-item">
                    <a href="">
                        <img src="img1">
                    </a>
                    <div class="in-lable">
                        <a href="link1">
                            <span class="title">title1</span>
                        </a>
                    </div>
                </div>
                <div class="img-item">
                    <a href="">
                        <img src="img2">
                    </a>
                    <div class="in-lable">
                        <a href="link2">
                            <span class="title">title2</span>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

针对这个结构,咱们可以写出精准的选择器,结合Puppeteer的API来获取你需要的元素。下面分几种常见场景来讲解:

1. 获取所有图片的链接(src属性)

要定位到这些图片,咱们可以用类选择器组合,确保只选中.img-item下的<img>标签,避免误选页面其他地方的图片:
选择器:.img-item img

在Puppeteer里获取所有图片src的代码示例:

const imageSrcs = await page.evaluate(() => {
  return Array.from(document.querySelectorAll('.img-item img')).map(img => img.src);
});
console.log('所有图片链接:', imageSrcs);

2. 获取所有标题文本和对应的跳转链接

标题文本在.title类的<span>里,跳转链接是它的父级<a>标签,咱们可以分别定位:

  • 标题文本选择器:.in-lable .title
  • 标题链接选择器:.in-lable a

获取标题和链接的代码:

const titleInfo = await page.evaluate(() => {
  return Array.from(document.querySelectorAll('.in-lable a')).map(link => ({
    title: link.querySelector('.title').textContent.trim(),
    url: link.href
  }));
});
console.log('标题及链接:', titleInfo);

3. 遍历每个列表项,同时获取图片和标题

如果需要把每个.list-item里的图片和标题对应起来,可以先选中所有列表项,再逐个提取内容:

const listItems = await page.evaluate(() => {
  return Array.from(document.querySelectorAll('.list-item')).map(item => {
    const img = item.querySelector('.img-item img');
    const titleLink = item.querySelector('.in-lable a');
    return {
      imageSrc: img ? img.src : null,
      title: titleLink ? titleLink.querySelector('.title').textContent.trim() : null,
      titleUrl: titleLink ? titleLink.href : null
    };
  });
});
console.log('列表项详情:', listItems);

重要提醒:处理动态加载的元素

如果你的页面是异步加载这段列表的,一定要先等待元素渲染完成再去获取,不然会拿到空结果。可以用Puppeteer的waitForSelector方法:

// 等待列表容器加载完成
await page.waitForSelector('.list-row');
// 之后再执行上面的获取逻辑

选择器的核心思路就是从最外层的容器开始缩小范围,用类名组合来精准定位,避免使用过于宽泛的标签选择器(比如直接用img或a),这样能减少误选的概率。

备注:内容来源于stack exchange,提问作者Oli Ver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.16 08:19:53