gpt4 book ai didi

node.js - 重用浏览器实例 puppeteer

转载 作者:行者123 更新时间:2023-12-05 00:46:30 26 4
gpt4 key购买 nike

我想知道是否有可能有一个 .js 文件打开浏览器实例,创建新页面/选项卡登录到网站(使用用户名/密码)并保持空闲状态。
并在第二个 .js 文件中使用文件一个浏览器实例及其页面。

1.js

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox'],
ignoreDefaultArgs: ["--hide-scrollbars"]
});

const page = await browser.newPage();
const response = await page.goto('https://google.com');

console.log('Browser open in the background (headless)!');
//await browser.close();
})();

2.js

const puppeteer = require('puppeteer');

(async () => {
// instructions on browser instance/page from 1.js ...
})();

最佳答案

The crawler object keeps the state of the browser instance and wherever you call/pass that instance, it refers to the same chromium in the "background". If this is an overkill, and you just want to connect to an already running chromium using puppeteer, you can do it with puppeteer.connect. take a look at this: How to "hook in" puppeteer into a running Chrome instance/tab – mbit

是的,我想这对我来说太过分了:)。但是您发布的链接是我想要的,但有 2 个问题。

这是我所拥有的样本。

// 1.js
// open chromium, new tab, go to google.com, print browserWSEndpoint, disconnect
const puppeteer = require('puppeteer');

(async () => {
var browser = await puppeteer.launch({headless: false});
var page = await browser.newPage();
var response = await page.goto('https://google.com');

var browserWSEndpoint = browser.wsEndpoint();
console.log(browserWSEndpoint); // prints: ws://127.0.0.1:51945/devtools/browser/6462daeb-469b-4ae4-bfd1-c3bd2f26aa5e

browser.disconnect();
})();

// 2.js
// connect to the open browser with the browserWSEndpoint manualy put in, ... , disconect.
const puppeteer = require('puppeteer');

(async () => {
var browser = await puppeteer.connect({browserWSEndpoint: 'ws://127.0.0.1:51945/devtools/browser/6462daeb-469b-4ae4-bfd1-c3bd2f26aa5e'});

// somehow use the tab that is open from 1.js (google.com)

await browser.disconnect();
})();

我从 console.log 1.js 获取 browserWSEndpoint 字符串。效果很好,但我有两个困难。

1 - 我如何使用来自 1.js 的变量 browserWSEndpoint,这样我就不必总是将其复制粘贴到 2.js。

2- 如果我在 1.js 上打开一个新页面/标签,然后去谷歌并断开连接 (browser.disconnect()),如何在 2.js 上使用该页面/标签。

关于node.js - 重用浏览器实例 puppeteer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60122534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com