我正在使用 puppeteer 检查网页上出现的特定文本。我要检查的代码如下:
if ((await page.waitForXPath('//span[contains(text(), "Subscription Confirmed")]',30000)) !== null) {
chk = await page.evaluate(el => el.innerText, await page.$x('//span[contains(text(), "Subscription Confirmed")]'))
chk = 'Success'
} else {
// do something else
chk = 'Failed'
}
这在开玩笑的测试中对我有用:
await page.waitForXPath('//*[contains(text(), "SOME TEXT")]')
尝试以下操作:
if ((await page.waitForXPath('//*[contains(text(), "Subscription Confirmed")]',30000)) !== null) {
chk = await page.evaluate(el => el.innerText, await page.$x('//*[contains(text(), "Subscription Confirmed")]'))
chk = 'Success'
} else {
chk = 'Failed'
}
您似乎只是在选择器中混淆了
span
和h1
。但是,我想提供一些建议和注意事项以改进其他答案。
"Success"
和 "Failed"
.waitForXPath
在超时到期时抛出,因此 if
是不必要的。waitForXPath
的第二个参数应该是{timeout: 30000}
而不是30000
。let
或 const
.waitFor_
的返回值而不是重新选择元素。waitForXPath
已弃用,取而代之的是 waitForSelector("::-p-xpath(...)")
.将这些建议放在一起,我们有:
const xp = '::-p-xpath(//h1[contains(text(), "Subscription Confirmed")])';
const el = await page.waitForSelector(xp);
const text = await el.evaluate(el => el.textContent);
如果你预计会失败,你可以用
try
/catch
包装它,或者使用速记:
const xp = '::-p-xpath(//h1[contains(text(), "Subscription Confirmed")])';
const el = await page.waitForSelector(xp).catch(() => null);
if (el) {
const text = await el.evaluate(el => el.textContent);
}
但我们可以改进这一点。 Puppeteer 现在有了更简洁的
::-p-text()
伪选择器:
const el = await page.waitForSelector("h1::-p-text(Subscription Confirmed)");
const text = await el.evaluate(el => el.textContent);
现在,由于您是通过全文选择而不是使用子字符串,所以您基本上已经知道文本,所以没有必要获取它!
如果你想检查特定文本是否存在并且不想等待它出现,你可以使用:
const exists = await page.$("h1::-p-text(Subscription Confirmed)");
if (exists) {
// it exists
}
如果找不到,exists
将为空,否则为 ElementHandle。这似乎更接近您的初衷。
有关在 Puppeteer 中按文本选择的规范资源,请参阅这篇文章。