const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    devtools: true,
    ignoreHTTPSErrors: true
  });

  const page = await browser.newPage();
  page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1');
  page.setViewport({
    width: 375,
    height: 667,
    isMobile: true
  });
  await page.goto('https://google.com', {
    waitUntil: 'networkidle2'
  });

  await page.evaluate(() => {
    console.log(window);
  })
})();


当我在setViewport()中将isMobile:true设置为铬时,铬通常会打开,但是该过程报告了以下错误:

(node:13360) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: net::ERR_ABORTED at https://google.com
(node:13360) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


怎么处理呢?

最佳答案

您只是错过了awaitsetUserAgent方法和setViewport方法。

(async () => {
 const browser = await puppeteer.launch({
   devtools: true,
   ignoreHTTPSErrors: true
 });

 const page = await browser.newPage();
 await page.setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1');
 await page.setViewport({
   width: 375,
   height: 667,
   isMobile: true
 });
 await page.goto('https://google.com', {
   waitUntil: 'networkidle2'
 });

 await page.evaluate(() => {
   console.log(window);
 })
})();


另外,您可以用emulate方法替换这些方法。

emulate方法是调用两个方法的快捷方式:


page.setUserAgent(userAgent)
page.setViewport(viewport)


别忘了从木偶戏中导入devices对象。查看devices的完整列表。

const devices = require('puppeteer/DeviceDescriptors');

await page.emulate(devices['iPhone 6'])


因此,您的最终脚本应为:

const puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');


(async () => {
 const browser = await puppeteer.launch({
   devtools: true,
   ignoreHTTPSErrors: true
 });

 const page = await browser.newPage();
 await page.emulate(devices['iPhone 6'])
 await page.goto('https://google.com', {
   waitUntil: 'networkidle2'
 });

 await page.evaluate(() => {
   console.log(window);
 })
})();

关于node.js - puppeteer 将“isMobile:true”设置为导致“UnhandledPromiseRejectionWarning”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57356255/

10-09 20:30