selenium使用location定位元素坐标偏差

本文探讨了使用Python+Selenium+Chromedriver进行元素坐标定位时出现的偏差问题,特别是通过location获取的坐标与截图坐标不匹配的情况。文章指出,此问题源于Windows系统显示缩放比例的设置,并提供了三种解决方案:调整显示设置、缩放截图图片或调整Image.crop参数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python+selenium+Chromedriver使用location定位元素坐标偏差
使用xpath定位元素,用.location获取坐标值,截取网页截图的一部分出现偏差。

之所以会出现这个坐标偏差是因为windows系统下电脑设置的显示缩放比例造成的,location获取的坐标是按显示100%时得到的坐标,而截图所使用的坐标却是需要根据显示缩放比例缩放后对应的图片所确定的,因此就出现了偏差。
解决这个问题有三种方法:
1.修改电脑显示设置为100%。这是最简单的方法;
2.缩放截取到的页面图片,即将截图的size缩放为宽和高都除以缩放比例后的大小;
3.修改Image.crop的参数,将参数元组的四个值都乘以缩放比例。

转载于:https://www.cnblogs.com/pythonClub/p/10498520.html

from io import BytesIO import numpy as np import time from PIL import Image from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.support import expected_conditions as EC import random class HeiMa: def __init__(self): self.url='http://mis-toutiao-python.itheima.net/#/' self.driver=webdriver.Chrome() self.driver.maximize_window() def login(self): self.driver.get(self.url) self.driver.find_element_by_class_name('yzm_btn').click() WebDriverWait(self.driver,20).until(EC.element_to_be_clickable((By.CLASS_NAME,'geetest_radar_tip'))) self.driver.find_element_by_class_name('geetest_radar_tip').click() WebDriverWait(self.driver,20).until(EC.presence_of_element_located((By.CLASS_NAME,'geetest_canvas_img'))) self.driver.execute_script('document.querySelectorAll("canvas")[2].style="display:block"') time.sleep(random.uniform(1, 2)) image1 = self.get_image('verify_code1.png') self.driver.execute_script('document.querySelectorAll("canvas")[2].style="display:none"') time.sleep(random.uniform(1,2)) self.driver.execute_script("document.getElementsByClassName('geetest_canvas_slice geetest_absolute')[0].style='display:none;'") time.sleep(random.uniform(1,2)) image2 = self.get_image('verify_code2.png') self.driver.execute_script("document.getElementsByClassName('geetest_canvas_slice geetest_absolute')[0].style='display:block;'") def get_image(self,image_file_name): image = self.driver.find_element(By.XPATH, '//*[@id="app"]/div/form') location=image.location size=image.size x1,y1=location['x'],location['y'] x2,y2=size['width']+location['x'],size['height']+location['y'] print(f'{x1},{y1},{x2},{y2}') screen_shot=self.driver.get_screenshot_as_png() screen_shot=Image.open(BytesIO(screen_shot)) captcha=screen_shot.crop((int(x1),int(y1),int(x2),int(y2))) captcha.save(image_file_name) return captcha if __name__=='__main__': heima=HeiMa() heima.login()为什么截图的位置不对
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值