我尝试启动一个浏览器并根据需要使用它,但我不知道如何将其设置为变量。
// return promise
puppeteer.launch()
这个:
// It's not working
let bro;
puppeteer.launch()
.then(res => bro = res);
这个:
//It's not working too
let bro;
puppeteer.launch()
.then(res => bro = res);
while (bro === undefined) {
}
bro.newPage();
请告诉我如何启动浏览器并在需要时使用它:
//
let bro
// launch browser
bro.newPage()
...
例如在 react 中我可以调用异步函数
axios.post("/postOnePage", data)
.then(res => {
this.setState({onePageCount: res.data.wordCount});
})
.catch(err => console.log(err))
将结果设置为变量并根据需要使用它
最佳答案
如果你使用 async/await
就很简单了:
const browser = await puppeteer.launch();
const page = await browser.newPage();
注意:将它包装在一个async
函数 中。
基本上 puppeteer.launch()
返回一个解析为浏览器实例的 promise 。所以你可以像上面那样简单地初始化一个变量来获取浏览器。我猜 then
会有点乱,你必须在 then
block 中工作。
const browser = puppeteer.launch();
browser.then((brw) => {
const page = brw.newPage();
page.then(pg => {
pg.goto('https://example.com').then(() => {
pg.screenshot({
path: 'example.png'
}).then(() => {
brw.close();
});
});
});
});
您也可以引用Puppeteer API .该文档带有示例,非常好。希望对您有所帮助。
编辑 1:
示例工作示例:
const puppeteer = require('puppeteer');
async function getScreenshot(page) {
await page.screenshot({
path: 'exampleShot.png'
});
}
async function newPageAndScreenshot(browser) {
const page = await browser.newPage();
await page.goto('https://www.github.com');
await page.screenshot({
path: 'github.png'
});
//you can also call getScreenshot here.
//await getScreenshot(page);
}
async function run() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
await getScreenshot(page);
await newPageAndScreenshot(browser);
//Some other function calls may be.
browser.close();
}
run();
希望对您有所帮助。
关于javascript - 如何将 puppeteer 浏览器设置为变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50660731/