在文档上下文里执行脚本,并返回结果

/在文档上下文里执行脚本,并返回结果
(async () => {
  const browser = await puppeteer.launch({
      args: ['--no-sandbox'],
      timeout: 10000,
    });
  const page = await browser.newPage();
  await page.goto('http://www.163.com');

  // Get the "viewport" of the page, as reported by the page.
  const dimensions = await page.evaluate(() => {
    return {
      width: document.documentElement.clientWidth,
      height: document.documentElement.clientHeight,
      deviceScaleFactor: window.devicePixelRatio
    };
  });

  console.log('Dimensions:', dimensions);

  await browser.close();
})();

//直接传递字符串

Passing arguments to pageFunction:

const result = await page.evaluate(x => {
  return Promise.resolve(8 * x);
}, 7);
console.log(result); // prints "56"

A string can also be passed in instead of a function:

console.log(await page.evaluate('1 + 2')); // prints "3"
const x = 10;
console.log(await page.evaluate(`1 + ${x}`)); // prints "11"

ElementHandle instances can be passed as arguments to the page.evaluate:

const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
await bodyHandle.dispose();

Shortcut for page.mainFrame().evaluate(pageFunction, ...args).

 

 

posted @ 2018-10-06 15:32  FromScratch  阅读(204)  评论(0编辑  收藏  举报