[python][selenium] on-screen position of element

前端 未结 3 1177
予麋鹿
予麋鹿 2020-12-16 07:29

Hello i would like to know the on-screen position of some element. I know how to get the position of element in python selenium webriver but how to get offset from left-top

相关标签:
3条回答
  • 2020-12-16 07:48

    The method get_window_position() of Selenium webdriver enables you to access the location of your browser with respect to your screen:

    #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"])
    
    0 讨论(0)
  • 2020-12-16 07:54

    I guess it's not possible to define distance from top-left corner of browser window to top-level corner of screen with just selenium. But you can try to implement following:

    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']
    
    0 讨论(0)
  • 2020-12-16 07:59

    There is no way to do this with 100% accuracy, but here is the best workaround that considers the browser window's offset, the toolbars in the window, and the scrolling position of the document:

    # 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)
    
    0 讨论(0)
提交回复
热议问题