英文内容来自:
Taking screenshots 截图
To capture a screenshot of a page, use the --screenshot
flag:
要对页面截图,只需使用--screenshot
参数即可:
1 2 3 4 5 6 7 chrome --headless --disable -gpu --screenshot https://www.baidu.com/ chrome --headless --disable -gpu --screenshot --window-size=1280,1696 https://www.baidu.com/ chrome --headless --disable -gpu --screenshot --window-size=412,732 https://www.baidu.com/
Running with --screenshot
will produce a file named screenshot.png
in 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 .
使用--screenshot
参数会在当前目录生成一个名为screenshot.png
的文件(编注:截图完成后浏览器会自动退出)。如果需要对整个页面截图的话还需要再加点东西。这里有一个David Schnurr写的博文《使用无界面Chrome作为自动截图工具》 可以参考一下。
编注:把鄙人之前那篇文章 提供一个在Selenium截网页长图的实现 稍微改动一下就可以了,之前那篇文章是接入现有浏览器,只需要改成无界面模式(headless)并且改成启动新的浏览器(chrome_options
里面不设置debugger_address
),网页截图完成后加一个driver.quit()
就可以自动关闭浏览器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from selenium import webdriverfrom time import sleepfrom base64 import b64decodefrom sys import argvoptions = webdriver.ChromeOptions() chrome_options.add_argument('--headless' ) chrome_options.add_argument('--disable-gpu' ) driver = webdriver.Chrome(options=options) driver.get("https://www.baidu.com" ) page_width = driver.execute_script("return document.body.scrollWidth" ) page_height = driver.execute_script("return document.body.scrollHeight" ) 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 }) with open('screenshot.png' , 'wb' ) as f: img = b64decode(res['data' ]) f.write(img) sleep(15 ) driver.execute_cdp_cmd('Emulation.clearDeviceMetricsOverride' , {}) driver.quit()