Pages

Five mistakes beginners make accessing web elements using xpath in Selenium


When I started learning selenium I wanted to work with absolute xpaths and focus on more complex stuff. As I moved on testing web pages I realized creating relative xpath to access web elements is unavoidable and can take a lot of time when you are a beginner. Below I summarize five common mistakes we all make accessing web elements through relative xpaths.
  1. Identifying an element when it contains a special character can throw unwanted errors and take a lot of time if you surround it with a single quote ('). Consider finding the element with text "Let's Talk Tea" with single quotes in example below:  System.out.println(driver.findElement(By.xpath("//*[contains(text(),'Let's Talk Tea\")]')).getTagName());
    Always surround your text with special characters \" and you are good to go!
     System.out.println(driver.findElement(By.xpath("//*[contains(text(),\"Let's Talk Tea\")]")).getTagName());

  2. Making xpath expressions with multiple conditions can simply be done with AND and OR keywords. This simple task can turn complex if you don't know these are case sensitive. Following xpath expressions are not same.
    driver.findElement(By.xpath(".//*[@type ='text' AND @id='email']")).sendKeys("test");
    driver.findElement(By.xpath(".//*[@type ='text' and  @id='email']")).sendKeys("test");

  3.  @type = 'text' and text() are not the same. @type = 'text'  selects web elements that have attribute type set as text in the DOM while text() is method used to find elements with exact text match.
  4. driver.findElement(By.xpath("//td[text()='UserID']"));// selects the WebElements displayed with text 'UserID' on the web page.
    driver.findElement(By.xpath("//input[@type()='text']"));// selects the web elements with input type text.


  5. 'following' and 'following-sibling' keywords can not be interchanged. 'following' selects the web elements in the current node while 'following-sibling'  selects nodes that are sibling to current node or in other words are on the same level as the current node.
  6. driver.findElements(By.xpath(".//*[@class='active']/following-sibling::li"));// returns all the elements in sibling nodes after the closing tag of the current node.
    driver.findElements(By.xpath("//*[@type='text']//following::input")); // returns all elements after the closing tag of the current node.


  7. 'child' and 'descendant' keywords can not be interchanged. 'child' selects the child web elements in the current node while 'descendant'  selects all child, grandchild elements in the nodes following current node.

  8.  driver.findElements(By.xpath(".//*[@class='wsb-navigation-rendered-top-level-menu ']/child::li");//returns all the child element of the current node.
    driver.findElements(By.xpath(".//*[@class='form-body']/descendant::div");// returns all child and grandchilds of the current node.


No comments:

Post a Comment