Selenium: 使用 Python 获取元素的坐标或尺寸

我发现有一些方法可以通过各种用于 Selenium 的 Java 库获取元素的屏幕位置和尺寸,例如 org.openqa.selenium.Dimension,它提供了 .getSize(),而 org.openqa.selenium.Point则提供了 getLocation()

有没有什么方法可以通过 Selenium Python 绑定获得元素的位置或尺寸?

136365 次浏览

Got it! The clue was on selenium.webdriver.remote.webelement — Selenium 3.14 documentation.

WebElements have the properties .size and .location. Both are of type dict.

driver = webdriver.Firefox()


e = driver.find_element_by_xpath("//someXpath")


location = e.location
size = e.size
w, h = size['width'], size['height']


print(location)
print(size)
print(w, h)

Output:

{'y': 202, 'x': 165}
{'width': 77, 'height': 22}
77 22

They also have a property called rect which is itself a dict, and contains the element's size and location.