我无法弄清楚这些包含异步函数的圆括号的用途。它们代表什么?
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// more codes here
})();
Run Code Online (Sandbox Code Playgroud) 我在使用 puppeteer 抓取用户时间轴上的所有推文 URL 时遇到问题。
使用 puppeteer,脚本应该在函数中 while 循环的每次迭代中向下滚动时间线,scrollToEnd直到到达底部。为了监视进度,我让脚本输出变量的值,该值是每次执行滚动之前评估的previousHeight当前值。scrollheightdocument.body
然而,一旦输出值变为 285,834,滚动就会停止。令人费解的是,该脚本既没有跳出 while 循环,也没有page.waitForFunction抛出超时错误。
我应该如何重写scrollToEnd函数或脚本的任何其他部分以便函数正确结束?
这是我的代码片段。为了简洁起见,省略了不相关的功能。
const puppeteer = require('puppeteer');
var UserUrls = ['https://twitter.com/someuser'];
// more functions here
async function scrollToEnd(
page,
ScrollDelay = 1000
) {
try {
let previousHeight = 0;
let notEnd = await page.waitForFunction(`document.body.scrollHeight > ${previousHeight}`);
while (notEnd) {
previousHeight = await page.evaluate('document.body.scrollHeight');
await page.evaluate('window.scrollBy(0, document.body.scrollHeight)');
await page.waitFor(ScrollDelay);
notEnd = await page.waitForFunction(`document.body.scrollHeight > ${previousHeight}`);
console.log(previousHeight)
};
return; …Run Code Online (Sandbox Code Playgroud) 我试图将自定义对象传递给page.evaluate(),但是当我运行脚本时,它将引发以下错误:
Error: Evaluation failed: TypeError: Cannot read property 'p1' of undefined。
如何在浏览器上下文中使用自定义对象?
const puppeteer = require('puppeteer');
function obj() {
this.p1 = 'a';
this.p2 = {
p21: 'b'
};
};
(async function () {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://stackoverflow.com/');
page.on('console', consoleObj => console.log(consoleObj.text()));
const obj1 = new obj();
await page.evaluate((obj1) => {
console.log(obj1.p1);
console.log(obj1.p2.p21);
console.log(obj1.p2.p21);
});
browser.close();
} catch (e) {
console.log(e);
};
})();
Run Code Online (Sandbox Code Playgroud)