【问题标题】:Puppeteer xpath expression failing, despite valid xpath expressionPuppeteer xpath 表达式失败,尽管 xpath 表达式有效
【发布时间】:2021-01-05 00:24:11
【问题描述】:

我有一个页面,其中包含屏幕截图中的表格,我正在尝试使用 puppeteer 进行抓取。我可以使用以下方法获取表格:

    //table[contains(@class, 'table') and .//th[contains(text(), 'Sqft')]]

(在开发工具中测试)。

现在我想用 puppeteer 得到它。我试过了:

    const page = await browser.newPage();
    try {

        await page.goto(URL).catch(console.error());
        var content = await page.content();
        const codeTableXpath = "//table[contains(@class, 'table') and .//th[contains(text(), 'Sqft')]]"


        const tableHTML = await content.waitForXPath(codeTableXpath).catch(console.error('xpath'));

当我单步执行代码时,错误发生在最后一行。如何获取表格 html 进行进一步处理?

编辑:

【问题讨论】:

    标签: javascript node.js xpath puppeteer


    【解决方案1】:

    page.content() 解析为包含页面完整 HTML 内容的字符串,而 waitForXPath()page 的方法。所以你需要这个(另外,.catch() 需要函数引用或函数表达式,而不是函数调用):

    const page = await browser.newPage();
    try {
      await page.goto(URL).catch(console.error); // function reference
    
      const codeTableXpath =
        "//table[contains(@class, 'table') and .//th[contains(text(), 'Sqft')]]";
    
      const table = await page.waitForXPath(codeTableXpath) // just page.waitForXPath()
        .catch(() => { console.error('xpath'); }); // function expression
    
      const tableHTML = await table.evaluate(element => element.outerHTML);
      // or: const tableHTML = await (await table.getProperty('outerHTML')).jsonValue();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多