CMDコマンドラインChromeは、Webページのスクリーンショットをファイルに自動的に取得し、スクリーンショットの完了後にブラウザーを自動的に終了します

スクリーンショットを撮る

Toページのスクリーンショットのキャプチャ、--screenshotフラグの使用
ページのスクリーンショットを作成するには、次の--screenshotパラメータを使用します。

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/

で実行する--screenshotscreenshot.png、現在の作業ディレクトリに名前が付けられたファイルが生成さます。フルページのスクリーンショットを探している場合は、少し複雑です。DavidSchnurrからのすばらしいブログ投稿があります。ヘッドレスChromeを自動スクリーンショットツールパラメータを
使用--screenshotすると、現在のディレクトリに名前が付けられたscreenshot.pngファイルが生成されます(編集者注:スクリーンショットが完了すると、ブラウザは自動的に終了します)。ページ全体のスクリーンショットを撮る必要がある場合は、何かを追加する必要があります。これは、DavidSchnurrが参考のために書いたブログ投稿「InterfacelessChromeを自動スクリーンショットツールとして使用する」です


編集者のメモ:Seleniumページの実現をカットするためにその記事を送信する前に、長いマップでできることを少し変更してください。記事が既存のブラウザーにアクセスする前に、インターフェイスモード(ヘッドレス)を変更して開始を変更する必要があるだけではありません。新しいブラウザ(chrome_options内部に設定されていませんdebugger_address)、Webページのスクリーンショットが完成した後にブラウザを追加すると、driver.quit()ブラウザを自動的に閉じることができます。

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()

おすすめ

転載: blog.csdn.net/qq_35977139/article/details/112347666