当我尝试使用 xpath 函数时,Playwright 未按预期工作。
这是我编写的用于抓取 <h1>
内文本的代码标签 https://example.org 。
const pw = require('playwright');
async function fetch(url) {
var browser = await pw.chromium.launch();
var context = await browser.newContext();
var page = await context.newPage();
await page.goto(url);
const h1 = await page.$('//h1')
console.log(await h1.evaluate(h1 => h1.innerHTML, h1));
await browser.close();
}
fetch('https://example.com')
执行后,此代码可以完美运行并显示,
Example Domain
但是如果我尝试使用 xpath 函数 text()
获取 h1 标记内的文本就像下面这样,
const h1 = await page.$('//h1/text()'); // also tried await page.$('xpath=//h1/text()');
console.log(await h1.evaluate(h1 => h1.textContent, h1));
它正在 throw ,
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'evaluate' of null
我做错了什么或者它不能与 xpath 函数一起使用吗?
最佳答案
正如 Michael 所说,$
函数的目的是返回一个 DOM 元素。如果您想计算 XPath 表达式,可以在 evaluate
函数中使用 document.evaluate
。
async function fetch(url) {
var browser = await playwright.chromium.launch();
var context = await browser.newContext();
var page = await context.newPage();
await page.goto(url);
console.log(await page.evaluate(() =>
document.evaluate('//h1/text()', document, null, XPathResult.STRING_TYPE).stringValue));
await browser.close();
}
fetch('https://example.com')
关于javascript - Xpath 函数在剧作家中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919509/