如果代理拒绝连接,Puppeteer 使用多个代理并更改自动代理

Joh*_*Dip 8 proxy node.js puppeteer

你能告诉我这是否可能吗?

我想使用多个代理并在代理拒绝连接时自动更改代理。

args: [
    '--proxy-server=127.0.0.1:9876', // Or whatever the address is
]
Run Code Online (Sandbox Code Playgroud)

因此,有了这个,您可以使用一个代理,但是如何使用多个代理并让它在拒绝连接时自动更改?

Gra*_*ler 12

使用 Tor。

您可以安装tor允许您通过 Tor 网络使用 Puppeteer 进行浏览软件包,并且可以非常轻松地更改您的身份(IP 地址)。

使用以下--proxy-server标志使用 Tor 启动 Puppeteer :

const browser = await puppeteer.launch({
  args: [
    '--proxy-server=socks5://127.0.0.1:9050',
  ],
});
Run Code Online (Sandbox Code Playgroud)

然后,在 上page.on('response')child_process.exec()如果响应不成功,则使用 ( response.ok() === false)更改代理。

以下命令将创建一个新的 Tor 身份:

(echo authenticate \'""\'; echo signal newnym; echo quit) | nc localhost 9051
Run Code Online (Sandbox Code Playgroud)

示例用法:

'use strict';

const puppeteer = require('puppeteer');
const exec = require('child_process').exec;

(async () => {
  const browser = await puppeteer.launch({
    args: [
      '--proxy-server=socks5://127.0.0.1:9050'
    ],
  });
  const page = await browser.newPage();
  let current_ip_address = '';
  
  page.on('response', response => {
    if (response.ok() === false) {
      exec('(echo authenticate \'""\'; echo signal newnym; echo quit) | nc localhost 9051', (error, stdout, stderr) => {
        if (stdout.match(/250/g).length === 3) {
          console.log('Success: The IP Address has been changed.');
        } else {
          console.log('Error: A problem occured while attempting to change the IP Address.');
        }
      });
    } else {
      console.log('Success: The Page Response was successful (no need to change the IP Address).');
    }
  });
  
  await page.goto('http://checkip.amazonaws.com/');
  
  current_ip_address = await page.evaluate(() => document.body.textContent.trim());
  
  console.log(current_ip_address);
  
  await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

注意: Tor 可能需要一些时间来更改身份,因此在继续您的程序之前验证 IP 地址是否不同可能是一个很好的调用。

  • 你这里的东西太棒了。我去实施它并且效果很好。不过,应该注意的是,`page.on('response'` 会检查每个请求,包括 css、图像、js 的请求。因此,如果您访问任何现代网页,您很容易就会有 10-20 个正在检查的请求因为其中很多都没有“ok()”状态,因此您最终会比平常想要的更频繁地切换。 (2认同)