首页 > 解决方案 > puppeteer 使用 alt 属性从 html 中获取 img

问题描述

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center"><!-- Start Product Photo --><div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1"><br><img src="/products/ca/downloads/images/54631_WIP.jpg" alt="Product image 2"><br><p>images not to scale</p></div><!-- End Product Photo --></div>

我有以下html。

通过 puppeteer,如何获取产品图像 2 的图像源(来自 alt = value 的源)

    product =  await page.evaluate(() => {
   let image = document.querySelector ("").src

    });

在 let 图像中,如何使用 dom 选择器锁定 alt 值 = Product image 2 的 img src?

任何帮助深表感谢。

标签: javascripthtmlnode.jspuppeteer

解决方案


您需要使用Attribute Selector。我相信您正在寻找的确切选择器是img[alt="Product image 2"]

let image = document.querySelector('img[alt="Product image 2"]').src;
console.log(image);
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 nopadding text-center">
  <!-- Start Product Photo -->
  <div class="row"><img src="/products/ca/downloads/images/54631.jpg" alt="Product image 1"><br><img src="/products/ca/downloads/images/54631_WIP.jpg" alt="Product image 2"><br>
    <p>images not to scale</p>
  </div>
  <!-- End Product Photo -->
</div>


推荐阅读