【发布时间】:2023-03-21 21:46:01
【问题描述】:
当我尝试使用 xpath 函数时,Playwright 没有按预期工作。
这是我为抓取https://example.org 的<h1> 标记内的文本而编写的代码。
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));
它在扔,
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'evaluate' of null
我是在做错什么,还是它不适用于 xpath 函数。
【问题讨论】:
-
我怀疑这是因为
h1(在您的第二个示例中)已经是一个文本节点,所以它没有属性textContent。所以我会尝试只评估h1看看会发生什么。 -
@JackFleeting 我试过了,它返回了
null。
标签: javascript node.js xpath web-scraping playwright