截屏
通过搜索文档,可以发现,Selenium 提供了以下两种类型的截屏功能:
-
[WebElement.screenshot(filename)][WebElement.screenshot]
:该方法可以对元素进行截屏,如下代码所示:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver import ChromeOptions options = ChromeOptions() options.add_argument('headless') with webdriver.Chrome(options=options) as driver: driver.get('https://www.jianshu.com') wait = WebDriverWait(driver,10) # 文章区域 el = wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR,'#list-container') )) # 浏览器窗口设置为元素大小,以保证能完全截取元素区域 driver.set_window_size(el.size['width'],el.size['height']) el.screenshot('D:\\jianshu.png')
WebDriver.save_screenshot(filename)
:截取浏览器当前页面。具体代码如下所示:
options = ChromeOptions() options.add_argument('headless') with webdriver.Chrome(options=options) as driver: driver.get('https://www.jianshu.com') wait = WebDriverWait(driver,10) # 文章区域 wait.until(EC.presence_of_element_located( (By.CSS_SELECTOR,'#list-container') )) width = driver.execute_script("return document.documentElement.scrollWidth") height = driver.execute_script("return document.documentElement.scrollHeight") print(f'page scroll size: {width} x {height}') # 将窗口设置为页面滚动宽高 driver.set_window_size(width, height) print('screenshot done') if driver.save_screenshot('D:\\jianshu.png') else print('screenshot failed!!')
注:截屏时我们需要将窗口的宽高设置为元素/页面滚动宽高,这样就可以完整截取整个元素/页面内容,但一个前提是必须使用 Headless 模式,否则窃取的只是当前视口高度内容。
标签:webdriver,screenshot,selenium,driver,截屏,操作,options From: https://www.cnblogs.com/yunlong-study/p/16594153.html