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

szm*_*zmo 4 python selenium position webdriver absolute

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

图片

小智 11

没有办法做到 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)
Run Code Online (Sandbox Code Playgroud)


And*_*son 9

我想不可能只用浏览器窗口的左上角到屏幕的顶层角来定义距离selenium.但您可以尝试实现以下内容:

driver = webdriver.Chrome()
driver.maximize_window() # now screen top-left corner == browser top-left corner 
driver.get("http://stackoverflow.com/questions")
question = driver.find_element_by_link_text("Questions")
y_relative_coord = question.location['y']
browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
y_absolute_coord = y_relative_coord + browser_navigation_panel_height
x_absolute_coord = question.location['x']
Run Code Online (Sandbox Code Playgroud)