python selenium 根据屏幕缩放比获取元素截图

获取元素截图,网上教程很多,但大部分都没有提到屏幕缩放比会影响到元素坐标,导致坐标不准确。

获取元素坐标都会用到:

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)  # 保存

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值