如何将所需的模块对象传递给 puppeteer page.evaluate
How to pass required module object to puppeteer page.evaluate
- 人偶版本:1.0.0
- 平台/OS版本:Windows10
- 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();
})();
- 人偶版本:1.0.0
- 平台/OS版本:Windows10
- 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();
})();