gpt4 book ai didi

javascript - 如何使用 puppeteer 从网站获取所有链接

转载 作者:行者123 更新时间:2023-12-04 11:47:10 24 4
gpt4 key购买 nike

好吧,我想要一种使用 puppeteer 和 for 循环来获取网站上的所有链接并将它们添加到数组中的方法,在这种情况下,我想要的链接不是 html 标签中的链接,它们是链接直接在源代码中,javascript文件链接等......我想要这样的东西:

array = [ ]
for(L in links){
array.push(L)
//The code should take all the links and add these links to the array
}
但是我怎样才能获得对 javascript 样式文件的所有引用以及网站源代码中的所有 URL?
我只是找到一个帖子和一个问题,教或展示它如何从标签中获取链接,而不是从源代码中获取所有链接。
假设您想获取此页面上的所有标签,例如:

view-source:https://www.nike.com/


如何获取所有脚本标签并返回控制台?我把 view-source:https://nike.com因为你可以获得脚本标签,我不知道你是否可以在不显示源代码的情况下做到这一点,但我考虑过显示和获取脚本标签,因为这是我的想法,但我不知道该怎么做它

最佳答案

可以仅使用 node.js 从 URL 获取所有链接,而无需 puppeteer:
主要有两个步骤:

  • 获取 URL 的源代码。
  • 解析链接的源代码。

  • node.js 中的简单实现:
    // get-links.js

    ///
    /// Step 1: Request the URL's html source.
    ///

    axios = require('axios');
    promise = axios.get('https://www.nike.com');

    // Extract html source from response, then process it:
    promise.then(function(response) {
    htmlSource = response.data
    getLinksFromHtml(htmlSource);
    });

    ///
    /// Step 2: Find links in HTML source.
    ///

    // This function inputs HTML (as a string) and output all the links within.
    function getLinksFromHtml(htmlString) {
    // Regular expression that matches syntax for a link (https://stackoverflow.com/a/3809435/117030):
    LINK_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/gi;

    // Use the regular expression from above to find all the links:
    matches = htmlString.match(LINK_REGEX);

    // Output to console:
    console.log(matches);

    // Alternatively, return the array of links for further processing:
    return matches;
    }
    示例用法:
    $ node get-links.js
    [
    'http://www.w3.org/2000/svg',
    ...
    'https://s3.nikecdn.com/unite/scripts/unite.min.js',
    'https://www.nike.com/android-icon-192x192.png',
    ...
    'https://connect.facebook.net/',
    ... 658 more items
    ]
    备注:
  • 为了简单起见,我使用了 axios 库并避免来自 nike.com 的“拒绝访问”错误。可以使用任何其他方法来获取 HTML 源,例如:
  • native node.js http/https 库
  • puppeteer 师 ( Get complete web page source html with puppeteer - but some part always missing )

  • 关于javascript - 如何使用 puppeteer 从网站获取所有链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67781393/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com