在 Puppeteer 中等待一个 xpath
·
问题:在 Puppeteer 中等待一个 xpath
在我用 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'替换第一行吗?
我试过 awaitpage.waitFor(linkEx),waitForSelector(linkEx)但它不起作用。
另外,我想用实际的 id (#activities) 或类似的东西替换第二行代码中的a,但我找不到合适的例子。
你能帮我解决这个问题吗?
解答
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')]")[0].href应该显示您希望点击的链接,否则您需要更改访问权限,或者您需要检查是否有更多元素具有相同的选择器等。这可能有助于找到更合适的选择器。
更多推荐

所有评论(0)