logo

如何在 Got 中设置代理

2024-06-27 23:18
本文介绍了5 个最佳的 Rust HTML 解析器,并推荐使用集蜂云管理来爬虫。

集蜂云是一个可以让开发者在上面构建、部署、运行、发布采集器的数据采集云平台。加入到数百名开发者中,将你的采集器发布到市场,从而给你带来被动收入吧!

Got 是一个流行的 JavaScript 库,用于 NodeJS 中的 HTTP 请求,也是一款出色的网页抓取工具。但尽管它具有所有有用的功能,但它却无法解决最重大的网页抓取挑战之一:被网站的反机器人保护系统拦截。

在本文中,您将了解如何通过设置 Got 代理来克服这一障碍。您将逐步了解使用代理进行网页抓取的过程,并了解哪些代理可以带来最佳效果。

步骤 1:使用 Got 设置代理

在使用 Got 设置代理之前,让我们先从一个要添加代理配置的基本脚本开始。

该脚本向 Web 服务发出直接的 HTTP 请求https://httpbin.io/ip,该 Web 服务返回请求客户端的 IP 地址。

import got from 'got';
 
try {
    // make HTTP request 
    const {body} = await got('https://httpbin.io/ip');
    // log the response
    console.log(body);
} catch (error) {
    console.error(error);
}


一旦完成所有设置,您就可以配置代理了。

但是,Got 并不支持开箱即用的代理。您必须与为 NodeJS 应用程序中的 HTTP 请求提供代理支持的代理进行集成。

有不同的 NodeJS 代理,但在本教程中,我们将使用hpagent最可靠的选项。hpagent采用与 Node.js 核心的 HTTP(s) 代理相同的参数和选项proxy,允许您指定代理 URL。

要使用 Got 设置代理,请配置hpagent必要的参数(代理 URL)并使用配置的代理发出请求。

首先hpagent使用以下命令进行安装。

npm install hpagent

之后,导入所需的库。然后,使用 定义代理配置选项hpagent。它涉及创建 HttpsProxyAgent 实例并指定代理 URL 和其他所需设置。

您可以从免费代理列表中获取免费代理,并使用以下格式构建 URL:。protocol:host:port您还应该使用 HTTPS 代理,因为它们适用于 HTTPS 和 HTTP 网站。

// import the required modules
import got from 'got';
import {HttpsProxyAgent} from 'hpagent';
 
const proxyOptions = {
    agent: {
        // create a new HttpsProxyAgent instance
        https: new HttpsProxyAgent({
            // add proxy settings
            keepAlive: true,
            keepAliveMsecs: 1000,
            maxSockets: 256,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            // specify proxy URL.
            proxy: 'http://20.219.180.149:3129'
        })
    }
};

最后,使用配置的选项提出您的请求。

//...
 
try {
    // make HTTP request
    const {body} = await got('https://httpbin.io/ip', proxyOptions);
    // log the response
    console.log(body);
} catch (error) {
    console.error(error);
}


把所有东西结合起来。你的完整代码应该如下所示:

// import the required modules
import got from 'got';
import {HttpsProxyAgent} from 'hpagent';
 
const proxyOptions = {
    agent: {
        // create a new HttpsProxyAgent instance
        https: new HttpsProxyAgent({
            // add proxy settings
            keepAlive: true,
            keepAliveMsecs: 1000,
            maxSockets: 256,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            // specify proxy URL.
            proxy: 'http://20.219.180.149:3129'
        })
    }
};
 
try {
    // make HTTP request
    const {body} = await got('https://httpbin.io/ip', proxyOptions);
    // log the response
    console.log(body);
} catch (error) {
    console.error(error);
}

运行它,结果应该是您的代理的 IP 地址。

{
  "origin": "20.219.180.149:45310"
}

代理身份验证 要验证已获得的代理,请使用以下格式指定您的代理protocol://username:password@IP:PORTURL :。

以下是如何修改上面的代码以进行验证的方法。

// import the required modules

import got from 'got';

import {HttpsProxyAgent} from 'hpagent';

 

const proxyOptions = {

    agent: {

        // create a new HttpsProxyAgent instance

        https: new HttpsProxyAgent({

            // add proxy settings

            keepAlive: true,

            keepAliveMsecs: 1000,

            maxSockets: 256,

            maxFreeSockets: 256,

            scheduling: 'lifo',

            // specify proxy URL.

            proxy: 'http://username:password@20.219.180.149:3129'

        })

    }

};

 

try {

    // make HTTP request

    const {body} = await got('https://httpbin.io/ip', proxyOptions);

    // log the response

    console.log(body);

} catch (error) {

    console.error(error);

}

第 2 步:使用 Got 旋转代理

网站通常会将“过多请求”标记为可疑活动,并可能阻止您的代理。为了避免此问题,您必须在多个代理之间轮换。这样,您的请求看起来会来自不同的用户或设备,从而增加您避免被检测到的机会。

让我们看看如何。

从免费代理列表中轮换 IP 要使用 Got 轮换代理,请指定代理池并为每个请求随机选择不同的代理。请按照以下步骤实现此目的。

将您的单个代理更改为代理列表,如下所示。

// import the required modules
import got from 'got';
import {HttpsProxyAgent} from 'hpagent';
 
// define a list of proxy URLs
const proxyList = [
  'http://20.219.180.149:3129',
  'http://198.199.70.20:31028',
  'http://8.219.97.248:80',
  // add more proxy URLs as needed
];

接下来,创建一个使用从列表中随机选择代理的函数Math.random()。

scraper.js
//...
 
// function to select a random proxy from the list
function getRandomProxy() {
  const randomIndex = Math.floor(Math.random() * proxyList.length);
  return proxyList[randomIndex];
}

在您的hpagent配置中,将proxy选项设置为getRandomProxy()功能。这将从列表中指定一个随机代理。

scraper.js
//...
const proxyOptions = {
    agent: {
        // create a new HttpsProxyAgent instance
        https: new HttpsProxyAgent({
            // add proxy settings
            keepAlive: true,
            keepAliveMsecs: 1000,
            maxSockets: 256,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            // specify proxy URL.
            proxy: getRandomProxy()
        })
    }
};

最后,使用配置的选项提出请求,就像在初始代理脚本中一样。

你的最终代码看起来应该是这样的:

scraper.js
// import the required modules
import got from 'got';
import {HttpsProxyAgent} from 'hpagent';
 
// define a list of proxy URLs
const proxyList = [
  'http://20.219.180.149:3129',
  'http://198.199.70.20:31028',
  'http://8.219.97.248:80',
  // add more proxy URLs as needed
];
 
// function to select a random proxy from the list
function getRandomProxy() {
  const randomIndex = Math.floor(Math.random() * proxyList.length);
  return proxyList[randomIndex];
}
 
const proxyOptions = {
    agent: {
        // create a new HttpsProxyAgent instance
        https: new HttpsProxyAgent({
            // add proxy settings
            keepAlive: true,
            keepAliveMsecs: 1000,
            maxSockets: 256,
            maxFreeSockets: 256,
            scheduling: 'lifo',
            // specify proxy URL.
            proxy: getRandomProxy()
        })
    }
};
 
try {
    // make HTTP request
    const {body} = await got('https://httpbin.io/ip', proxyOptions);
    // log the response
    console.log(body);
} catch (error) {
    console.error(error);
}

要验证它是否有效,请发出多个请求。每次都应该获得不同的 IP 地址。以下是两个请求的结果:

{
  "origin": "8.219.64.236:1416"
}
 
{
  "origin": "20.219.180.149:45310"
}

然而,虽然这种方法可能在教程中有效,但它可能会在大多数实际用例中失败,特别是当您计划大规模抓取时。

亲自看看。尝试使用 Got 代理脚本抓取下面的G2 评论页面。

// import the required modules

import got from 'got';

import {HttpsProxyAgent} from 'hpagent';

 

// define a list of proxy URLs

const proxyList = [

  'http://20.219.180.149:3129',

  'http://198.199.70.20:31028',

  'http://8.219.97.248:80',

  // add more proxy URLs as needed

];

 

// function to select a random proxy from the list

function getRandomProxy() {

  const randomIndex = Math.floor(Math.random() * proxyList.length);

  return proxyList[randomIndex];

}

 

const proxyOptions = {

    agent: {

        // create a new HttpsProxyAgent instance

        https: new HttpsProxyAgent({

            // add proxy settings

            keepAlive: true,

            keepAliveMsecs: 1000,

            maxSockets: 256,

            maxFreeSockets: 256,

            scheduling: 'lifo',

            // specify proxy URL.

            proxy: getRandomProxy()

        })

    }

};

 

try {

    // make HTTP request

    const {body} = await got('https://www.g2.com/products/visual-studio/reviews', proxyOptions);

    // log the response

    console.log(body);

} catch (error) {

    console.error(error);

}

您将收到类似以下的错误消息。

HTTPError: Response code 403 (Forbidden)

如您所见,免费代理无法帮助您避免被高级反机器人措施阻止。为了解决这个问题,让我们探索高级代理。

集蜂云是一个可以让开发者在上面构建、部署、运行、发布采集器的数据采集云平台。平台提供了海量任务调度、三方应用集成、数据存储、监控告警、运行日志查看等功能,能够提供稳定的数据采集环境。平台提供丰富的采集模板,简单配置就可以直接运行,快来试一下吧。

导航目录