我想在运行puppeteer时使用以下CSS选择器来查找HTML元素。
法典:
let items = await page.$$eval('a.a-link-normal[href~="/product/"] > img', nodes => nodes.map(n => { ... }));
它不返回任何内容。当我删除"
时,它说它无效。 当我在 https://try.jsoup.org/上尝试选择器时,它工作得很好。
当我使用正则表达式运行稍微修改的代码时,它也可以工作:
let items = await page.$$eval('a.a-link-normal > img', nodes =>
nodes.map(n => {
console.log(n.href.match(/product/)) // returns something
...
})
);
我哪里犯了错误?
要检查的示例 HTML 代码:
<td class="productRowColumn">
<a class="a-link-normal" href="/product/testprod/asc/">
<img alt="" src="sampleimg.jpg" aria-hidden="true" height="28" width="45" title="sampleProductTitle">
</a>
</td>
要回答您的问题,
您应该切换[href~="/product/"]
以[href^="/product/"]
或[href*="/product/"]
~=
存在包含单词(不是您需要的(。
^=
存在始于。
*=
包含子字符串。
导致您的 css 选择器如下所示:
'a.a-link-normal[href^="/product/"] > img'
语法~=
属性选择器表示属性中具有该单词的属性。该单词必须以空格分隔,因此您的代码将处理以下内容:
<a class="a-link-normal" href="/product/ testprod/asc/">
但并非没有空格。
所需的选择器是 *=
或 ^=
。正如 MDN 上描述的那样:
[attr*=value]
表示属性名称为 attr 的元素,其值在字符串中至少包含一个值。
[attr^=value]
表示属性名称为 attr 的元素,其值以值为前缀(前面(。