获取元素截图,网上教程很多,但大部分都没有提到屏幕缩放比会影响到元素坐标,导致坐标不准确。
获取元素坐标都会用到:
imgelement = driver.find_element_by_xpath(xpath) location = imgelement.location # x,y轴坐标
但是location 获取的是屏幕缩放比例为100%的坐标,如果你屏幕缩放比例不为100%,那么实际截图的时候就会不准确,所以要结合屏幕缩放比例来获取。
# -*- coding: UTF-8 -*-
import datetime
import os
import win32api, win32gui, win32print
from PIL import Image
from win32.lib import win32con
def get_scaling():
'''获取屏幕的缩放比例'''
hDC = win32gui.GetDC(0)
real_wide = win32print.GetDeviceCaps(hDC, win32con.DESKTOPHORZRES) #获取真实的分辨率宽
screen_wide = win32api.GetSystemMetrics(0) #获取缩放后的分辨率宽
proportion = round(real_wide / screen_wide, 2)
return proportion
'''
截取验证码图片
'''
def get_ele_screen(driver, xpath, img_name=None):
if not img_name:
img_name = datetime.datetime.now().strftime('%H%M%S')
dir_path = "D:/logs/code_dir"
Full_screen_path = os.path.join(dir_path, img_name+'-FullScreen.png')
driver.save_screenshot(Full_screen_path)
imgelement = driver.find_element_by_xpath(xpath) # 定位
location = imgelement.location # 获取验证码x,y轴坐标
size = imgelement.size # 获取元素的长宽
scaling = get_scaling() # 获取屏幕缩放比例
rangle = (int(location['x'])*scaling, int(location['y'])*scaling, int(location['x'] + size['width'])*scaling,
int(location['y'] + size['height'])*scaling) # 写成我们需要截取的位置坐标
i = Image.open(Full_screen_path) # 打开截图
frame4 = i.crop(rangle) # 使用Image的crop函数,从截图中再次截取我们需要的区域
eleimg_name = img_name+'-ele.png'
eleImg_path = os.path.join(dir_path, eleimg_name)
frame4.save(eleImg_path) # 保存