javascript - 在 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
那个,但我找不到合适的例子。
你能帮我解决这个问题吗?
解决方案
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
应该显示您希望单击的链接,否则您需要更改访问权限,或者您需要检查是否有更多元素具有相同的选择器等。这可能有助于找到更合适的选择器。
推荐阅读
- c - 使用信号量时程序进入无限循环(死锁)
- laravel - 2个laravel项目交叉请求之间的问题
- c - 函数中的堆与函数参数重叠
- python - 从玩家那里得到输入后,猜数字游戏停止
- react-native - React Native - expo 构建 web 生产
- core-data - SwiftUI 中的 Core Data 观察对象
- java - Android Studio Firebase 存储问题
- python - step 参数在 Slicing 中如何工作?
- reactjs - 为什么 this.state 在 messageParser 中显示为空
- ios - 在 swift 网络调用之前显示一个 progressHud