【问题标题】:How to get redirected final url with Got in Node.js如何在 Node.js 中使用 Got 获得重定向的最终 url
【发布时间】:2021-02-15 19:48:40
【问题描述】:

我需要访问十万个或更多的 url,并检查它们是否重定向到不同的最终 url。

我正在使用https://www.scrapeulous.com 来执行此操作。但我需要编写一个简单的自定义函数来使其工作。 Scrapeulous 使用 got 库。其中有documentation that on the followRedirects option that notes:

跟随重定向

类型:布尔默认值:true

定义是否应自动遵循重定向响应。

请注意,如果服务器发送 303 响应任何请求 类型(POST、DELETE等),Got会自动请求资源 通过 GET 在位置标头中指向。这是按照 规范。

also notes 用于 Response.url:

网址

类型:字符串

请求 URL 或重定向后的最终 URL。

我试过以下代码无济于事:

class Get extends HttpWorker {
  async crawl(url) {
    let result = await this.Got(encodeURI(url),
    {followRedirect: true});
    return result.url;
  }
}

我以前从未写过任何 javascript 或 node.js,所以要温柔。让我们使用重定向到 experiit.com 的 debianit.com 作为我的示例。旁注:我还希望能够提供代码域而不是 url,以确定站点是否默认为 http:// 或 https://。但是一次一个解决方案对我来说就足够了:)。

我还尝试返回整个结果对象并查看它,但没有发现任何用处。

【问题讨论】:

    标签: node.js puppeteer


    【解决方案1】:

    编辑:对此有更清楚的说明。

    首先,重定向分为三种类型(this answer):

    1. HTTP - 作为响应标头中的信息(代码为 301、302、3xx)
    2. HTML - 作为 HTML 中的标记(维基百科:元刷新)
    3. JavaScript - 像 window.location = new_url 这样的代码

    关于示例域,debianit.com。它通过javascript重定向到experait.com。特别是这个脚本:

      <script>
       var url= "https://www.experaIT.com"; 
        window.location = url;
      </script>
    

    Got 文档声明它将遵循重定向:

    如果服务器发送 303 响应任何请求类型

    换句话说,它似乎不会遵循元或 javascript 重定向。虽然您可以解析生成的 html 并从 javascript window.location 或元标记中提取 url。

    显然,使用 BrowserWorker 类而不是 HttpWorker 类也可以。这是适用于此的草率代码。

    class Render extends BrowserWorker {
      async crawl(url) {
        await this.page.goto(url, {
          waitUntil: 'networkidle2', // two open connections is okay
        });
    
        return await this.page.url();
      }
    }
    

    至于我关于如何找出正确的协议以附加到域名的旁注。根据this answer chromium 没有与 chrome 相同的多功能框功能,但是,per this answer about the selenium python browser, 您可以通过附加 http:// 并让 chromium 解决这个问题,如果页面重定向到 https:// 与否。

    【讨论】:

      猜你喜欢
      • 2012-01-10
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-08
      • 2011-04-03
      • 1970-01-01
      相关资源
      最近更新 更多