gpt4 book ai didi

javascript - 在 Puppeteer 中等待 xpath

转载 作者:行者123 更新时间:2023-12-04 14:37:11 25 4
gpt4 key购买 nike

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

await page.waitFor(5000)

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

if (linkEx.length > 0) {
await linkEx[0].click()
}
你知道如何用等待实际文本替换第一行 'Shop' ?
我试过等待 page.waitFor(linkEx) , waitForSelector(linkEx)但它不起作用。
另外,我想替换 a在具有实际 id ( #activities ) 或类似内容的第二行代码中,但我找不到合适的示例。
你能帮我解决这个问题吗?

最佳答案

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应该显示您希望单击的链接,否则您需要更改访问权限,或者您需要检查是否有更多元素具有相同的选择器等。这可能有助于找到更合适的选择器。

关于javascript - 在 Puppeteer 中等待 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62320494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com