使用Selenium可以通过locationsize属性来获取元素在网页中的实际位置。

首先,使用find_element()方法找到你想要获取位置的元素。然后,可以使用location属性获取元素的位置,以像素为单位。例如:

element = driver.find_element_by_xpath("//div[@id='element-id']")
location = element.location
print("元素在页面中的位置:(x={}, y={})".format(location['x'], location['y']))

接下来,你可以使用size属性获取元素的大小,以像素为单位。例如:

size = element.size
print("元素的宽度和高度:(width={}, height={})".format(size['width'], size['height']))

请注意,元素的位置是相对于整个页面的左上角的坐标。如果页面发生滚动,可以使用execute_script()方法来滚动到指定位置。例如,要滚动到页面的中间,可以使用以下代码:

driver.execute_script("window.scrollTo(0, document.body.scrollHeight/2)")

这将使页面滚动到其高度的一半的位置。

希望这可以帮助到你!

selenium 如何获取一个元素 在网页中的实际位置呢。。比如我已经滚动到了中间了

原文地址: https://www.cveoy.top/t/topic/i4by 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录