【问题标题】:NightmareJS : "Failed to execute 'querySelector' on 'Document': '#LINK1$1' is not a valid selector."NightmareJS:“无法在 'Document' 上执行 'querySelector':'#LINK1$1' 不是有效的选择器。”
【发布时间】:2018-06-08 05:12:48
【问题描述】:

我正在使用 NightmareJS 来抓取网站的数据,并且该网站使用 id 作为锚标记,其方式与下面的代码类似。

<div>
    <a id="#LINK1$1"></a>
</div>

我正在尝试使用 '.click(Selector)' 方法,该方法默认使用 querySelector,但我似乎无法通过 id 获取锚标记。 我都试过了

.click('#LINK1$1'),
.click('\u{0023}LINK\u{0031}\u{0024}\u{0031}')

但它们都导致相同的错误

"Failed to execute 'querySelector' on 'Document': '#LINK1$1' is not a valid selector."

我该怎么办?

【问题讨论】:

    标签: javascript nightmare


    【解决方案1】:

    您可以使用 Xpath 方式来执行此操作。 Puppeteer 有一个 xpath 函数。

    理论

    来自他们的文档,

    page.$x(expression)
    expression <string> Expression to evaluate.
    returns: <Promise<Array<ElementHandle>>>
    The method evaluates the XPath expression.
    

    它将返回一个元素数组。我们可以随意click他们。

    练习

    获取元素的xpath,

    现在应用它,

    // we execute the xpath
    const elems = await page.$x(`//*[@id="#LINK1$1"]`)
    
    // We click the first element, since it returns an array
    await elems[0].click();
    

    完成!

    顺便说一句,这也适用于浏览器,

    function getElementByXpath(path) {
      return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
    }
    getElementByXpath(`//*[@id="#LINK1$1"]`)
    // >> Returns single node <a id=​"#LINK1$1">​Test​</a>​
    

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2021-11-04
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多