在单独的js文件中导出异步函数的结果,在另一个javascript文件中导入结果



尝试构建一个小刮刀。为了重用功能,我认为"页面对象模型"会派上用场。

在main.js我需要多个小脚本,在下面的例子中只有一个模型(GooglePage)。脚本可以工作。但我想知道如何从google.js脚本传递一个值回主脚本。我想在main.js脚本中使用'pageCountClean'变量的值,以便在应用程序的其余部分使用。

一直在寻找关于在脚本之间传递值和函数的信息。要从页面构造函数导出值,请使用promise await导出函数。但是我迷路了。我必须使用承诺吗?当前的需求/导入和导出方式是否足以创建脚本之间的关系?欢迎指教。

////////////main.js

const { chromium } = require('playwright');
const { GooglePage } = require('./models/Google');
(async () => {
const browser = await chromium.launch({ headless: true, slowMo: 250 });
const context = await browser.newContext();
const GoogleUrl80 = https://www.google.nl/search?q=site%3Anu.nl;
// Cookie consent:
console.log('Cookie consent - start');
const page80 = await browser.newPage();
await page80.goto('https://google.nl');
await page80.waitForTimeout(1000);
await page80.keyboard.press('Tab');
await page80.keyboard.press('Tab');
await page80.keyboard.press('Enter');
console.log('Cookie Consent - done');
// Number of urls in google.nl (using google.js)
await page80.goto(GoogleUrl80, {waitUntil: 'networkidle'});
const googlePage80 = new GooglePage(page80);
await googlePage80.scrapeGoogle();
// Want to console.log 'pageCountClean' here.
await browser.close()
})()

////////////Google.js

class GooglePage {
constructor(page) {
this.page = page;
}
async scrapeGoogle() {
const GoogleXpath = '//div[@id="result-stats"]';
const pageCount = await this.page.$eval(GoogleXpath, (el) => el.innerText);
const pageCountClean = pageCount.split(" ")[1];
console.log(pageCountClean);
}
}
module.exports = { GooglePage };

您可以从async函数返回pageCountClean,并在main.js文件中返回await:

在Google.js:

async scrapeGoogle() {
const GoogleXpath = '//div[@id="result-stats"]';
const pageCount = await this.page.$eval(GoogleXpath, (el) => el.innerText);
const pageCountClean = pageCount.split(" ")[1];
console.log(pageCountClean);
return pageCountClean;
}

在main.js:

const googlePage80 = new GooglePage(page80);
const result = await googlePage80.scrapeGoogle();
console.log(result);

最新更新