当我尝试使用 puppeteer 登录 sisal.it 站点时,http 登录请求失败并返回错误代码 403(禁止),使用相同帐户但手动打开浏览器进行登录请求时请求成功。如果我用 puppeteer 打开浏览器并手动执行登录过程,请求就会失败
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
headless: false,
ignoreDefaultArgs: ['--enable-automation']
});
const page = await browser.newPage();
// Navigate to the page that will perform the tests.
await page.setViewport({ width: 1366, height: 1024});
await page.setExtraHTTPHeaders({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"Cache-Control": "max-age=0",
"Access-Control-Allow-Origin": "https://areaprivata.sisal.it"
});
await page.goto('https://chrome.google.com/webstore');
await page.waitForNavigation();
await page.goto('https://areaprivata.sisal.it/loginJwt');
await page.waitForSelector('input[name="usernameEtc"]');
await page.type('input[name="usernameEtc"]', 'TEST');
await page.keyboard.press('Tab');
await page.keyboard.down('Shift');
await page.keyboard.type('t');
await page.keyboard.up('Shift');
await page.keyboard.type('est');
await page.click('#buttonAuth');
})();
在执行登录之前,我尝试传递几个参数和标头,正如您从上面的代码中看到的那样。 如果我传递这些参数,它甚至不会发送请求,但会返回一些 cors 错误。
我猜,sisal.it 已经实施了严格的检测方法来防止自动访问,尤其是登录等操作。这是使用 Puppeteer 等自动化工具时的常见挑战,但是您可以采取几个步骤来使您的脚本更安全有弹性并更紧密地模仿人类行为。
首先,考虑将
puppeteer-extra
与 puppeteer-extra-plugin-stealth
插件集成。该插件旨在通过自动应用多种规避技术来规避几种常见的检测技术。安装必要的软件包并调整您的代码,如下所示:
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
(async () => {
const browser = await puppeteer.launch({
headless: false,
ignoreDefaultArgs: ['--enable-automation']
});
const page = await browser.newPage();
// Your existing code to navigate and login
})();
此外,您当前设置自定义 HTTP 标头的方法是朝着正确方向迈出的一步,但必须确保这些标头不会无意中发出自动访问信号。特别注意
User-Agent
字符串和其他签名标头,例如 Sec-Fetch-*
,它们可以通过反自动化检查进行仔细审查。理想情况下,从合法的、人工驱动的浏览器会话中捕获这些标头,并尽可能在 Puppeteer 脚本中复制它们。
此外,考虑在击键和操作(例如单击登录按钮)之间引入故意的、随机的延迟,以更令人信服地模仿人类行为。