问题
I'm testing out puppeteer for chrome browser automation ( previously using selenium but had a few headaches with browser not waiting until page fully loaded ) .
When I launch an instance of puppeteer - then it displays the contents taking up less than half the screen with scroll bars. How can I make it take up a full screen?
const puppeteer = require('puppeteer');
async function test(){
const browser = await puppeteer.launch({
headless: false,
});
const page = await browser.newPage();
await page.goto('http://google.com')
}
test()
The initial page seems to load fine , but as soon as I access a page it makes it scrollable and smaller.
回答1:
You probably would want to set a certain screen size, which any real browser has:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 768});
await page.goto('https://example.com', {waitUntil: 'networkidle2'});
await page.screenshot({path: 'example.png'});
browser.close();
})();
回答2:
you can user options in launch
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
args:[
'--start-maximized' // you can also use '--start-fullscreen'
]
});
const page = await browser.newPage();
await page.setViewport({ width: 1366, height: 768});
await page.goto('https://example.com', {waitUntil: 'networkidle2'});
await page.screenshot({path: 'example.png'});
browser.close();
})();
回答3:
const puppeteer = require('puppeteer-core');
(async () => {
const browser = await puppeteer.launch({
headless: false,
defaultViewport: null,
});
const pages = await browser.pages();
const page = pages[0];
await page.goto('https://google.com');
})();
Source: https://github.com/GoogleChrome/puppeteer/issues/3688#issuecomment-453218745
回答4:
According to the Puppeteer Documentation:
page.setViewport(viewport)
viewport
<Object>
width
<number> page width in pixels.height
<number> page height in pixels.deviceScaleFactor
<number> Specify device scale factor (can be thought of as dpr). Defaults to1
.isMobile
<boolean> Whether themeta viewport
tag is taken into account. Defaults tofalse
.hasTouch
<boolean> Specifies if viewport supports touch events. Defaults tofalse
isLandscape
<boolean> Specifies if viewport is in landscape mode. Defaults tofalse
.- returns: <Promise>
NOTE in certain cases, setting viewport will reload the page in order to set the
isMobile
orhasTouch
properties.In the case of multiple pages in a single browser, each page can have its own viewport size.
Therefore, you can use page.setViewport() to set the page width and height:
await page.setViewport({
width: 1366,
height: 768,
});
Note: Make sure to use the await operator when calling page.setViewport(), as the function is asynchronous.
来源:https://stackoverflow.com/questions/48013969/how-to-maximise-screen-use-in-pupeteer-non-headless