[python] [selenium]元素的屏幕位置

时间:2017-03-15 10:53:12

标签: python selenium webdriver position absolute

你好我想知道一些元素的屏幕位置。我知道如何在python selenium webriver中获取元素的位置但是如何从屏幕的左上角获得偏移?

image

3 个答案:

答案 0 :(得分:6)

我想我们不可能只用Math.max定义从浏览器窗口左上角到屏幕顶层角落的距离。但您可以尝试实施以下内容:

selenium

答案 1 :(得分:0)

无法做到100%准确,但这是考虑浏览器窗口的偏移量,窗口中的工具栏以及文档的滚动位置的最佳解决方法:

# Assume there is equal amount of browser chrome on the left and right sides of the screen.
canvas_x_offset = driver.execute_script("return window.screenX + (window.outerWidth - window.innerWidth) / 2 - window.scrollX;")
# Assume all the browser chrome is on the top of the screen and none on the bottom.
canvas_y_offset = driver.execute_script("return window.screenY + (window.outerHeight - window.innerHeight) - window.scrollY;")
# Get the element center.
element_location = (element.rect["x"] + canvas_x_offset + element.rect["width"] / 2,
                    element.rect["y"] + canvas_y_offset + element.rect["height"] / 2)

答案 2 :(得分:0)

Selenium Webdriver的方法get_window_position()使您可以访问浏览器相对于屏幕的位置:

#Get the current location of your browser 
browser_location = driver.get_window_position()
# eg: {'y': 127, 'x': 15}

# Set the absolute position of your Web element here (top-left corner)
element_location = (element.location["x"]+ browser_location["x"],
                    element.location["y"]+ browser_location["y"])