Selenium: get coordinates of element


636
636 points
selenium get coordinates of element
selenium get coordinates of element

Selenium get coordinates of element

Testing UI can prove to be a quite tricky job when you try to do in automation. In UI testing my experience one essential piece is to know the coordinates of element. We’ll try to see how we can use selenium to get coordinates of an element.

Get coordinates of element using javascript
 # @return [Array] of x,y position of element
    def element_position(element)
      Capybara.evaluate_script <<-EOS
        function() {
          var element = document.evaluate('#{element.path}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
          var rect = element.getBoundingClientRect();
          return [rect.left, rect.top];
        }();
      EOS
    end
Get coordinates of element using WebElements properties

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

element = find('locator')

element.location

Returns :

{'y': 300, 'x': 278}

Having the location it’s a handy thing but sometimes you might want to know the size of the locator and perform some assertions against that as well.

element = find('locator')

element.size

Returns :

{'width': 20, 'height': 30}

For me having this 2 informations , element size and element location I can do a proper UI test is just you need to handle all these information based on the screen resolution you are testing on.

Advertisements

Other useful articles :

How to use : Capybara get attribute

Introducing the Tellurium Selenium Automated Testing Framework


Like it? Share with your friends!

636
636 points
Test engineer

0 Comments

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.