1. 程式人生 > 實用技巧 >Python Selenium 自動化實現截圖操作

Python Selenium 自動化實現截圖操作

一、今天小編就為大家分享一篇對 Python 獲取螢幕截圖的 3 種方法詳解

1、採用 selenium 中的兩種截圖方法

  • 方法一:save_screenshot()
  • 方法二:get_screenshot_as_file()
    • 用法一樣,都是擷取瀏覽器當前窗口裡的內容
from PIL import ImageGrab
import time

def screenshot_image1(webdriver, image_path):
    nowTime = time.strftime("%Y-%m-%d_%H-%M-%S")
    imageName = image_path + "
/" + "bug_image{}.png".format(nowTime) webdriver.save_screenshot(imageName) def screenshot_image2(webdriver, image_path): nowTime = time.strftime("%Y-%m-%d_%H-%M-%S") imageName = image_path + "/" + "bug_image{}.png".format(nowTime) webdriver.get_screenshot_as_file(imageName)

2、方法三:Windows 環境下截圖需要用到 PIL 庫,使用 pip 安裝 PIL 庫

  • pip install pillow
  • 函式引數介紹如下,預設為全屏截圖
"""
第一個引數 開始截圖的x座標
第二個引數 開始截圖的y座標
第三個引數 結束截圖的x座標
第四個引數 結束截圖的y座標
"""
bbox = (0, 0, 1920, 1080)
im = ImageGrab.grab(bbox)   # grab() 預設截全屏
  • 用例輸出如下
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from screenshot.ScreenShotFunc import
* class Test_Baidu_Search(unittest.TestCase): def setUp(self) -> None: self.driver = webdriver.Chrome() self.driver.get("https://www.baidu.com") self.driver.maximize_window() self.driver.implicitly_wait(10) def tearDown(self) -> None: time.sleep(2) self.driver.quit() def test01(self): self.driver.find_element(By.ID, "kw").send_keys("Python") time.sleep(2) self.driver.find_element(By.ID, "su").click() # time.sleep(3) title = self.driver.title # 呼叫第一種方法實現截圖 """ try: self.assertIn("Python", title) except Exception as E: image_path = "D:\work_doc\CodeFile\dcs_class6\screenshot_image" screenshot_image1(self.driver, image_path) raise AssertionError(E) """ # 呼叫第二種方法實現截圖 """ try: self.assertIn("Python", title) except Exception as E: image_path = "D:\work_doc\CodeFile\dcs_class6\screenshot_image" screenshot_image2(self.driver, image_path) raise AssertionError(E) """ # 呼叫第三種方法實現截圖 try: self.assertIn("Python", title) except Exception as E: image_path = "D:\work_doc\CodeFile\dcs_class6\screenshot_image" screen_shot(image_path) raise AssertionError(E) if __name__ == '__main__': unittest.main()