【问题标题】:puppeteer - click anchor containing a span with matching textpuppeteer - 单击包含具有匹配文本的跨度的锚点
【发布时间】:2021-03-07 09:04:55
【问题描述】:

我正在尝试让 puppeteer 单击具有包含某些文本的子跨度的锚点。

HTML sn-p(个人详细信息被“...”删除):

<a data-url="/accounts/inquiry/accountdetails/..." class="account-title-group column " tabindex="0" role="link">
        <i class="icon acct-tile  checking"></i>
    <span class="account-name OneLinkNoTx" lang="en">
        Checking</span>
    <span class="masked-account-number has-wells-advisor">
        <span class="OneLinkNoTx">...</span>
    </span>
</a>

我尝试了几种变体都无济于事:


  //const aElementsWithChecking = await page.$x("//a[contains(., 'Checking')]");
  //const aElementsWithChecking = await page.$x("//a[@class='account-title-group' and descendant::span[contains(., 'Checking')]]");
  //const aElementsWithChecking = await page.$x("//a[@class='account-title-group' and descendant::span[contains(text(), 'Checking')]]");
  //const aElementsWithChecking = await page.$x("//a[@class='account-title-group' and .//*[contains(text(), 'Checking')]]");
  //const aElementsWithChecking = await page.$x("//a[@class='account-title-group' and .//*[contains(., 'Checking')]]");
  const aElementsWithChecking = await page.$x("//a[(.//*|.)[.='Checking']]");

  if (aElementsWithChecking.length > 0) {
    await aElementsWithChecking[0].click();
  } else {
    throw new Error("Link not found");
  }

【问题讨论】:

  • //a[contains(., 'Checking')] 应该有效。如果它不在那里,您可能必须等待它。
  • 我继续与 Abdel 一起进行故障排除。这个错误似乎是问题[Report Only] Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'nonce-........' https: 'unsafe-inline' 'unsafe-eval'". Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list. 运行page.setBypassCSP(true) 并不能解决问题。
  • await page.setBypassCSP(true) ?也可以尝试 args:['--disable-web-security'] 作为 puppeteer 选项

标签: javascript web-scraping puppeteer


【解决方案1】:

如果您尝试根据 innerHTML 选择锚标记 你必须尝试:

await page.$$eval("a",
                  anchors=>anchors.filter(
                           anchor=>anchor.innerHTML
                                         .includes("checking"))[0].click());

【讨论】:

  • 我尝试了最初的建议,但实际上得到了错误TypeError: anchors[0].click is not a function。我显然不适合这里。
  • 我在我的机器上尝试了一个类似的案例,如果你可以发送 URL,它可以工作,我可以帮助你
  • 尝试最后一次编辑并判断是否出现任何错误
  • wellsfargo.com(显然只有在您在那里有帐户时才能使用)。我试过你更新的代码。它不会出错(我所有的人都这样做了),但它实际上也没有点击链接。
  • 您可以尝试console.log(anchors[0]) 看看它是否在page.$$eval 回调中是正确的
猜你喜欢
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多