这是我的代码:
const puppeteer = require('puppeteer');
const varname = require('varname');
...
const page = await browser.newPage();
await page.goto(url);
let generalInfo = await page.evaluate(() => {
let elements = Array.from(document.querySelectorAll('#order-details > table > tbody > tr'));
let res = {};
elements.map((tr) => {
let split = tr.innerText.trim().split('\t');
res[varname.camelback(split[0])] = split[1]; // Here is: ... Error: Evaluation failed: ReferenceError: varname is not defined
});
return res;
});
...
await browser.close();
显示错误:
UnhandledPromiseRejectionWarning:未处理的承诺 rejection(拒绝ID:1):错误:评估失败:ReferenceError: varname未定义
答案 0 :(得分:3)
您想在浏览器上下文中使用模块varname
。要实现这一点,您应该使用page.addScriptTag()
将varname
注入浏览器,如下所示:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.addScriptTag({ path: './node_modules/varname/build/varname.js' });
const generalInfo = await page.evaluate(() => {
return window.varname.camelback('foo_bar_baz');
});
console.log(generalInfo); // prints fooBarBaz
await browser.close();
})();