Relative Locators in Selenium

Relative Locators are an important addition to Selenium

Source code for Selenium is available on github.com. Here is the full path to the code for Relative Locators

github.com/SeleniumHQ/selenium/tree/trunk/py/selenium/webdriver/support

  1. above() – finds an element or elements located above a fixed element.
  2. below() – finds an element or elements located below a fixed element.
  3. near() – finds an element or elements located near a fixed element.
  4. toLeftOf() – finds an element or elements located to the left of a fixed element.
  5. toRightOf() – finds an element or elements located to the right of a fixed element.

The implementation of relative location is not obvious.  Web-pages are laid out dynamically by the browser.  The upper left corner of the entire web-page is 0,0. Each visible element has a base location offset from 0,0 and a size in height and width. There is no empty space in a web-page, everything is occupied by an element. If the web-page is resized all the elements are resized proportionally. Elements may change relative positions. What is confusing about the relative locator function is that elements positioned to the right may be put down and underneath so that the element is no longer to the right it’s towards the bottom. Another potential problem is nearness. I am not certain but I have seen a definition of nearness as being within 50 pixels. Resize the page and your nearness numbers may increase or decrease and breaks a test(s). With a different devices “nearness” may vary and cause mandatory test rewrites. nearness can’t be calibrated. the default is XX. 

The Relative Locator functions return a list of elements that meet the criteria. The list may be empty if no element(s) match the criteria. The searches you make are tag limited. When you search you must specify the type of element that you are looking for not just all the elements within range of your original element.