0


Selenium之截图方式

1、get_screenshot_as_file

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.get_screenshot_as_file("./img/save.png")
driver.quit()

get_screenshot_as_file方法只能截取当前页面全屏

2、save_screenshot()

save_screenshot()其实和save_screenshot_as_file()用法相同,两者没什么区别,我们可以看下save_screenshot()的封装

使用时最后返回的还是save_screenshot_as_file()方法

3、get_screenshot_as_png()

get_screenshot_as_png()方法截取后直接是二进制,并不能像前两个方法一样直接生成图片,我们再写入本地即可。

from selenium import webdriver
from selenium.webdriver.common.by import By
 
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
img_save = driver.find_element(by=By.XPATH, value="//img[@id='s_lg_img']")
a = driver.get_screenshot_as_png()  # 截取后直接是二进制
with open("./img/two01.jpg", mode="wb")as f:
    f.write(a)
driver.quit()

以上用法是截取页面全屏,还可根据定位的元素截取相应的图片

img_save = driver.find_element(by=By.XPATH, value="//img[@id='s_lg_img']")
a = img_save.screenshot_as_png  # 截取后直接是二进制,无括号
with open("./img/two01.jpg", mode="wb")as f:
    f.write(a)
driver.quit()

4、get_screenshot_as_base64()

get_screenshot_as_base64()截取后的图片是以base64加密过的,需要解密后再写入本地。

import base64
 
from selenium import webdriver
from selenium.webdriver.common.by import By
 
driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.implicitly_wait(10)
img_save = driver.find_element(by=By.XPATH, value="//img[@id='s_lg_img']")
a = driver.get_screenshot_as_base64()  # base64加密
 
b = base64.b64decode(a)  # 解密
with open("./img/two.jpg", mode="wb")as f:
    f.write(b)
driver.quit(

与get_screenshot_as_png()相似的是可根据定位的元素截取相应的图片

img_save = driver.find_element(by=By.XPATH, value="//img[@id='s_lg_img']")
a = img_save.screenshot_as_base64  # base64加密,无括号
b = base64.b64decode(a)  # 解密
with open("./img/two.jpg", mode="wb")as f:
    f.write(b)
标签: selenium chrome python

本文转载自: https://blog.csdn.net/m0_72165796/article/details/128362012
版权归原作者 勤奋的鸟 所有, 如有侵权,请联系我们删除。

“Selenium之截图方式”的评论:

还没有评论