【问题标题】:Failed to scrape the link to the next page using xpath in puppeteer在 puppeteer 中使用 xpath 抓取到下一页的链接失败
【发布时间】:2021-09-17 06:18:32
【问题描述】:

我正在尝试从webpage 中抓取指向下一页的链接。我知道如何使用 css 选择器来抓取它。但是,当我尝试使用 xpath 解析相同的内容时出现问题。 This 是我得到的,而不是下一页链接。

const puppeteer = require("puppeteer");
let url = "https://stackoverflow.com/questions/tagged/web-scraping";
 
(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    
    await page.goto(url,{waitUntil: 'networkidle2'});
    let nextPageLink = await page.$x("//a[@rel='next']", item => item.getAttribute("href"));
    // let nextPageLink = await page.$eval("a[rel='next']", elm => elm.href);
    console.log("next page:",nextPageLink);
    await browser.close();
})();

如何使用 xpath 抓取到下一页的链接?

【问题讨论】:

    标签: javascript node.js web-scraping xpath puppeteer


    【解决方案1】:
    1. page.$x(expression) 返回一个元素句柄数组。您需要解构或索引访问才能从数组中获取第一个元素。
    2. 要从此元素句柄获取 DOM 元素属性,您需要使用元素句柄参数或元素句柄 API 进行评估。
    const [nextPageLink] = await page.$x("//a[@rel='next']");
    const nextPageURL = await nextPageLink.evaluate(link => link.href);
    

    或者:

    const [nextPageLink] = await page.$x("//a[@rel='next']");
    const nextPageURL = await (await nextPageURL.getProperty('href')).jsonValue();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-23
      相关资源
      最近更新 更多