CMD command line Chrome to automatically take screenshots of web pages to files, and automatically exit the browser after the screenshot is completed

Taking screenshots

A Capture A Screenshot of the To Page, The use --screenshotIn Flag:
To screenshot of the page, just use the --screenshotparameters to:

chrome --headless --disable-gpu --screenshot https://www.baidu.com/

# Size of a standard letterhead. 标准的信件比例
chrome --headless --disable-gpu --screenshot --window-size=1280,1696 https://www.baidu.com/

# Nexus 5x
chrome --headless --disable-gpu --screenshot --window-size=412,732 https://www.baidu.com/

Running with --screenshotwill produce a file named screenshot.pngin the current working directory. If you're looking for full page screenshots, things are a tad more involved. There's a great blog post from David Schnurr that has you covered. Check out Using headless Chrome as an automated screenshot tool .
Using --screenshotparameters will generate a screenshot.pngfile named in the current directory (Editor's note: the browser will automatically exit after the screenshot is completed). If you need to take a screenshot of the entire page, you need to add something. Here is a blog post "Using Interfaceless Chrome as an Automatic Screenshot Tool" written by David Schnurr for reference.


Editor's note: Before I sent that article to provide a cut in the realization of Selenium pages long map a little change what you can, before the article is to access existing browser, not only need to change the interface mode (headless) and change Start a new browser ( chrome_optionsnot set inside debugger_address), add one after the screenshot of the web page is completed, and the driver.quit()browser can be closed automatically.

from selenium import webdriver
from time import sleep
from base64 import b64decode
from sys import argv

# 改成启动新的浏览器,使用headless无界面浏览器模式
options = webdriver.ChromeOptions() 
# 增加无界面选项
chrome_options.add_argument('--headless') 
# 如果不加这个选项,有时定位会出现问题
chrome_options.add_argument('--disable-gpu') 
# 启动浏览器
driver = webdriver.Chrome(options=options)

# 访问页面,这里可以改成获取启动参数 argv[1]
driver.get("https://www.baidu.com")

# 取出页面的宽度和高度
page_width = driver.execute_script("return document.body.scrollWidth")
page_height = driver.execute_script("return document.body.scrollHeight")

# 直接开启设备模拟,不要再手动开devtools了,否则截图截的是devtools的界面!
driver.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', {
    
    'mobile':False, 'width':page_width, 'height':page_height, 'deviceScaleFactor': 1})

# 执行截图
res = driver.execute_cdp_cmd('Page.captureScreenshot', {
    
     'fromSurface': True})

# 返回的base64内容写入PNG文件
with open('screenshot.png', 'wb') as f:
    img = b64decode(res['data'])
    f.write(img)

# 等待截图完成
sleep(15)

# 关闭设备模拟
driver.execute_cdp_cmd('Emulation.clearDeviceMetricsOverride', {
    
    })

# 关闭浏览器
driver.quit()

Guess you like

Origin blog.csdn.net/qq_35977139/article/details/112347666