簡體   English   中英

您如何從帶有節點puppeteer的頁面獲取所有鏈接?

[英]How do you get all the links from a page with node puppeteer?

我正在嘗試使用node構建Web搜尋器,並遇到了puppeteer程序包,該程序包非常適合我想要的內容。 我的最終結果是收集頁面的所有鏈接,頁面的所有文本內容,然后是頁面本身的屏幕截圖。

我執行了以下操作,它似乎收集了大量鏈接,但是在實際檢查站點時,有一些鏈接沒有收集。

const puppeteer = require('puppeteer');

module.exports = () => {
  (async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://pixabay.com/en/columbine-columbines-aquilegia-3379045/');
    await page.screenshot({ path: 'myscreenshot.png', fullPage: true });
    let text = await page.$eval('*', el => el.innerText.split(' '));
    text = text.map(string => {
      return string.replace(/[^\w\s]/gi, '');
    });

      let hrefs = await page.evaluate(() => {
          const links = Array.from(document.querySelectorAll('a'))
          return links.map(link => link.href);
      });
    console.log('done');

    await browser.close();
  })();
};

例如,以下鏈接: /go/?t=image-details-shutterstock&id=699165328在href數組中不存在。 更糟糕的是,這些是引出該站點的鏈接,是我想要做的確切類型,否則,我只能抓取一個站點。

我的腳本僅顯示某些鏈接是有原因的嗎? 查詢選擇器是否太狹窄或拒絕某些鏈接?

鏈接是由onclick事件生成的,例如保存在data-go屬性中

<a data-go="image-details-shutterstock&amp;id=458320033">

它只需要添加/go/?t=並獲得它

return links.map(link => link.href || link.getAttribute('data-go'));

也有菜單的空白鏈接,例如

<a><i class="icon icon_menu_user"></i></a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM