selenium - 截取页面图片和截取某个元素的图

1.截取页面图片并保存

  • 在测试过程中,是有必要截图,特别是遇到错误的时候进行截图。
# coding:utf-8
from time import sleep
from PIL import Image
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
sleep(2)
driver.get_screenshot_as_file('D:\\baidu.png')  # 把截取的图片存放在D盘
driver.quit()

2.截取某个元素的图

pip install pillow
# coding:utf-8
from time import sleep
from PIL import Image
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.baidu.com")
sleep(2)
driver.save_screenshot('baidu.png')  # 截取当前页面全图
element = driver.find_element_by_id("su")  # 百度一下的按钮
print("获取元素坐标:")
location = element.location
print(location)

print("获取元素大小:")
size = element.size
print(size)

# 计算出元素上、下、左、右 位置
left = element.location['x']
top = element.location['y']
right = element.location['x'] + element.size['width']
bottom = element.location['y'] + element.size['height']

im = Image.open('baidu.png')
im = im.crop((left, top, right, bottom))
im.save('D:\\baidu.png')

 

posted @ 2023-10-18 15:07  小林同学_Scorpio  阅读(240)  评论(0编辑  收藏  举报
1