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.
如何处理?
答案 0 :(得分:0)
您正在使用异步等待,并且代码中存在一些错误,并且没有用于该代码的处理程序,因此,每当我们使用异步等待时,都应将代码放在try catch块中,这是一个好习惯以try开头的函数并以catch结束函数,因此,每当发生错误时,它都会进入catch块。
(async () => {
try {
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);
})
} catch(error) {
console.log("handle the error here", error)
}
})();
答案 1 :(得分:0)
您刚刚错过了await
方法和setUserAgent
方法的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
方法是调用两个方法的快捷方式:
请不要忘记从操纵up中导入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);
})
})();