我正在创建一个网络 api,它可以抓取给定的 url 并将其发回。我正在使用 Puppeteer 来执行此操作。我问了这个问题:Puppeteer not behaving like in Developer Console
并收到一个答案,表明它只有在 headless 设置为 false 时才有效。我不想不断打开我不需要的浏览器用户界面(我只需要数据!)所以我在寻找为什么 headless 必须是假的,我能得到一个让 headless = true 的修复程序吗.
这是我的代码:
express()
.get("/*", (req, res) => {
global.notBaseURL = req.params[0];
(async () => {
const browser = await puppet.launch({ headless: false }); // Line of Interest
const page = await browser.newPage();
console.log(req.params[0]);
await page.goto(req.params[0], { waitUntil: "networkidle2" }); //this is the url
title = await page.$eval("title", (el) => el.innerText);
browser.close();
res.send({
title: title,
});
})();
})
.listen(PORT, () => console.log(`Listening on ${PORT}`));
最佳答案
它可能在 UI 模式下工作但不是 headless 的原因是积极对抗抓取的网站会检测到您正在运行 headless 浏览器。
一些可能的解决方法:
使用puppeteer-extra
在这里找到:https://github.com/berstend/puppeteer-extra 查看他们的文档以了解如何使用它。它有几个插件可能有助于通过 headless 模式检测:
puppeteer-extra-plugin-anonymize-ua
-- 匿名化您的用户代理。请注意,这可能有助于通过 headless 模式检测,但如果您访问 https://amiunique.org/ 就会看到这一点。这不太可能足以阻止您被识别为重复访客。puppeteer-extra-plugin-stealth
-- 这可能有助于赢得不被检测为 headless 的猫鼠游戏。有许多技巧可用于检测 headless 模式,也有许多技巧可用来规避它们。
运行“真正的”Chromium 实例/UI
可以让您将 puppeteer 附加到正在运行的实例的方式运行单个浏览器 UI。这是一篇解释它的文章:https://medium.com/@jaredpotter1/connecting-puppeteer-to-existing-chrome-window-8a10828149e0
本质上,您是使用 --remote-debugging-port=9222
(或任何旧端口?)以及其他命令行开关从命令行启动 Chrome 或 Chromium(或 Edge?)在你运行它的环境中。然后你使用 puppeteer 连接到正在运行的实例,而不是让它执行启动 headless Chromium 实例的默认行为: const browser = await puppeteer.connect({ browserURL: ENDPOINT_URL });
。在此处阅读 puppeteer 文档以获取更多信息:https://pptr.dev/#?product=Puppeteer&version=v5.2.1&show=api-puppeteerlaunchoptions
当您使用 --remote-debugging-port=9222
选项从命令行启动浏览器时,ENDPOINT_URL
会显示在终端中。
此选项将需要一些服务器/操作 mojo,因此请准备好进行更多的 Stack Overflow 搜索。 :-)
我敢肯定还有其他策略,但这是我最熟悉的两种策略。祝你好运!
关于javascript - 为什么 headless 需要假才能让 Puppeteer 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63818869/