【问题标题】:How can I capture all links in a page with Puppeteer?如何使用 Puppeteer 捕获页面中的所有链接?
【发布时间】:2021-01-12 20:54:45
【问题描述】:

尝试捕获页面中的所有<a>

console.log 返回未定义,但我不明白为什么 这是const anchors = Array.from(document.querySelectorAll(sel)); 正确吗?

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
                                            headless: false,
                                            userDataDir: "C:\\Users\\johndoe\\AppData\\Local\\Google\\Chrome\\User Data\\Default"
                                        });
  const page = await browser.newPage();
  await page.setViewport({
    width: 1920,
    height: 1080,
    deviceScaleFactor: 1,
  });
  await page.goto('https://www.facebook.com/groups/632312010245152/members');
  
  //https://github.com/puppeteer/puppeteer/blob/main/examples/search.js
  let membri = await page.evaluate((sel) => { 
    const anchors = Array.from(document.querySelectorAll(sel));
    return anchors;
  }, 'a');
  console.log(membri);
})();

【问题讨论】:

  • 谢谢,我得到并返回了元素的属性(href),以便拥有一个可序列化的数组const serializableLinks = anchors.map(x => x.getAttribute("href")); //<-- convert to string
  • 请记住,x.getAttribute("href") 可能会返回相对 URL。如果您需要绝对 URL,请改用 x.href

标签: javascript node.js web-scraping puppeteer


【解决方案1】:
const findLinks = await page.evaluate(() =>
  Array.from(document.querySelectorAll("a")).map((info) => ({
    information: info.href.split()
  }))
);
links = [];
findLinks.forEach((link) => {
  if (link.information.length) {
    links.push(link.information);
  }
});
await console.log(links);
await page.close();
return links;

不确定这是否是最优化的解决方案,但它确实有效。如果您可以向我发送此代码的清理版本,我将不胜感激:)

【讨论】:

    【解决方案2】:
    const arrayList = await page.evaluate(() => {
    const nodeListLinks = document.querySelectorAll('a'),
          array = [...nodeListLinks],
          list = array.map(({href}) => ({href}))
    return arrayList
    })
    
    console.log(arrayList)
    

    【讨论】:

    • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票。
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
    猜你喜欢
    • 2021-04-18
    • 2019-05-16
    • 2021-08-19
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    相关资源
    最近更新 更多