在我找到的每个例子中,我总是看到对puppeter的调用以及main函数中的browser和page对象。我想这是上下文访问的问题。
但是有可能归档我正在寻找的内容,并且仍然能够在页面对象文件中至少使用页面对象吗?
main.mjs
import Browser from './browser.mjs'
import HomePage from './HomePage.mjs'
async function main () {
const browser = new Browser();
const homePage = new HomePage(browser.page);
await homePage.open();
console.log(await homepage.getTitle());
await browser.close();
}
main();
浏览器.mjs
class Browser {
constructor() {
return this.main(); // I know, that's ugly
}
async main() {
this.browser = await puppeteer.launch({
headless: false,
});
this.page = await browser.newPage();
return this.browser,this.page
}
}
export default Browser
class HomePage {
constructor(page) {
this.page = page;
}
async open() {
this.page.goto('http://www.contoso.com');
}
async getTitle() {
return this.page.title();
}
}
export default HomePage