>木偶版:1.0.0
>平台/操作系统版本:Windows 10
> Node.js版本:8.9.3
这是我的代码:
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: Unhandled promise
rejection (rejection id: 1): Error: Evaluation failed: ReferenceError:
varname is not defined
解决方法:
您想在浏览器上下文中使用模块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();
})();