首页 > 解决方案 > 在 Puppeteer 中等待 xpath

问题描述

在我用 Puppeteer 抓取的页面上,我有一个列表,每个li. 我正在尝试在此列表中查找并单击具有特定文本的元素。我有以下代码:

await page.waitFor(5000)

const linkEx = await page.$x("//a[contains(text(), 'Shop')]")

if (linkEx.length > 0) {
  await linkEx[0].click()
}

您知道如何用等待实际文本替换第一行'Shop'吗?

我试过 await page.waitFor(linkEx)waitForSelector(linkEx)但它不起作用。

另外,我想a用实际的 id ( ) 或类似的东西替换第二行代码中的#activities那个,但我找不到合适的例子。

你能帮我解决这个问题吗?

标签: javascriptweb-scrapingxpathpuppeteer

解决方案


page.waitForXPath你在这里需要什么。

例子:

const puppeteer = require('puppeteer')

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

  // await page.waitForSelector('//a[contains(text(), "More information...")]') // ❌
  await page.waitForXPath('//a[contains(text(), "More information...")]') // ✅
  const linkEx = await page.$x('//a[contains(text(), "More information...")]')
  if (linkEx.length > 0) {
    await linkEx[0].click()
  }

  await browser.close()
}
fn()

试试这个基于 id 的 xpath:

"//*[@id='activities' and contains(text(), 'Shop')]"

你可知道?如果您在 Chrome DevTools 的“元素”选项卡中右键单击一个元素并选择“复制”:您可以在此处复制元素的确切选择器或 XPath。之后,您可以切换到“控制台”选项卡,并使用 Chrome API 测试选择器的内容,以便为您的 puppeteer 脚本准备它。例如:$x("//*[@id='activities' and contains(text(), 'Shop')]").href应该显示您希望单击的链接,否则您需要更改访问权限,或者您需要检查是否有更多元素具有相同的选择器等。这可能有助于找到更合适的选择器。


推荐阅读