脚本无法产生所需的结果

Script unable to yield the desired result

我在 node.js 中编写了一个与 puppeteer 相关的脚本,用于从网页的多个帖子中抓取第一个 title。当我执行以下脚本时,它既不获取任何结果也不抛出任何错误。

这是我的尝试:

const puppeteer = require('puppeteer');
const url = "https://whosebug.com/questions/tagged/web-scraping";

(async function main() {
    const browser = await puppeteer.launch();
    const page    = await browser.newPage();
    page.on('console', obj => console.log(obj._text));
    await page.goto(url);
    await page.waitForSelector('.question-hyperlink');
    await page.$(() => {
        let item = $eval('.question-hyperlink').innerText;
        console.log(item);
    })
    await browser.close();
})();

Although I know that if I bring about the following change into my above script, it will work. However, I would like to stick to the way I tried above so that I can understand how .$eval() works in this very case.

await page.evaluate(() => {
    let item = document.querySelector('.question-hyperlink').innerText;
    console.log(item);
})

page.$(selector) means 你想得到指定选择器的第一个元素的句柄,但是你没有给它任何选择器,这就是它不起作用的原因。

相反,您可以获得所需元素的句柄:

const link = await page.$('.question-hyperlink');

然后获取该元素所需属性的句柄,最后获取其值:

let valueHandle = await link.getProperty('textContent');
console.log(await valueHandle.jsonValue());

更简单、更清晰的解决方案

您可以在找到元素时将所需的元素选择器和函数提供给 page.$eval 运行。

const linkTitle = await page.$eval('.question-hyperlink', el => el.textContent);
console.log(linkTitle);