【问题标题】:Puppeteer: Find element by HTML attributePuppeteer:通过 HTML 属性查找元素
【发布时间】:2020-01-01 15:05:04
【问题描述】:

基本上,我试图让 Puppeteer 通过其属性 data-form-field-value 在此页面上找到一个元素,该属性必须等于 244103310504090

这是按钮的 HTML 代码:

<section class="fl-accordion-tab--content">
<div class="fl-product-size">
</button><button class="fl-product-size--item fl-product-size--item__is- 
selected" type="button" data-form-field-target="SKU" data-form-field-base-css- 
name="fl-product-size--item" data-form-field-value="244103310504090" data-form- 
field-unselect-group="" data-testid="fl-size-244103310504-US-9" data-product- 
size-select-item="244103310504090" data-form-field-selected="true">
<span>9</span>
</button></div>
</section>

我尝试了一些方法,但似乎找不到解决方案,感谢您的帮助!

【问题讨论】:

  • 嗨!想展示这段代码you've tried?此外,您的 HTML 看起来很奇怪,因为 &lt;/button&gt; 结束标记不合适。

标签: javascript node.js puppeteer


【解决方案1】:

查看 Puppeteer 的 documentation,您需要为您指定的属性构造一个元素选择器。

attribute selectors 的 MDN 文档解释了如何执行此操作:

const puppeteer = require('puppeteer');

puppeteer.launch().then(async browser => {
  const page = await browser.newPage();
  await page.goto('https://example.com');

  // Select the element using the attribute
  const element = await page.$('[data-form-field-value="244103310504090"]');

  // ...
});

【讨论】:

  • 嗯,是的,我已经设置了一个元素选择器,但是我尝试过的所有 xpath 包括您刚刚建议的那个都不起作用...这是有效的对象的实际 xpath:@987654324 @ 但显然我试图通过它的属性来查找元素,而不是通过这个确切的 xpath
  • 您确定使用page.$ 而不是page.xpath?请您粘贴您正在使用的确切代码 - 此函数应使用标准 CSS 选择器而不是 XPath
  • 是的,我肯定在使用page.$,请在此处查看我的代码:const [sizeOption] = await page.$('[data-form-field-value="244103310504090"]'); if (sizeOption) { await sizeOption.click(); }
  • page.$ 只会返回一个元素(page.$$ 返回一个数组),您应该能够将该代码重写为:const sizeOption = await page.$('[data-form-field-value="244103310504090"]'); if (sizeOption) { await sizeOption.click(); }
  • 但这与我在上面发送的代码完全相同,只是没有 .click() 函数所需的 const 周围的 []
猜你喜欢
  • 2012-07-08
  • 2020-10-30
  • 2012-06-30
  • 2013-11-03
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多