Selenium WebDriver - Using normalize-space in Xpath

What is normalize-space in selenium?

Normalize-space is a very useful function in XPath when you build it with reference to some string or keyword to use it in the selenium test script and it has leading or trailing intermediate repeating white space. Normalize-space will strip such leading and trailing white space. In Selenium webdriver, very often we use keyword references in building xpath. If there is not any good reference to build xapth then it is mandatory to use such keywords as reference.

You can look at my post describing different ways to build xpath .

Example of normalize space in selenium

Here I am presenting one example where we will use normalize-space function to build xpath and use it in the Selenium webdriver test script.


normalize-space in xpath

Look at the above image. You can see that the label France contains leading and trailing space. Now if you want to use the keyword France in xpath building, You must strip space. Otherwise, it won't work for you. So here, the Normalize-space function will help you to strip leading and trailing space.

What is the difference between text and normalize-space in XPath?

text() method will match the text of an element. However, normalize-space will first strip leading and trailing white space and then it will match the text.

Selenium test script for normalize space

Complete selenium script demonstrates the usage of normalize-space as below.
package test;
import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class basic { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","D:\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("https://only-testing-blog.blogspot.com/2014/01/textbox.html"); driver.findElement(By.xpath("//*[@id=\"check3\"]")).click(); //Used Normalize-space to strip leading and trailing space. driver.findElement(By.xpath("//*[normalize-space(text())='France']")).click(); //working copy } }

In the above given normalize space in selenium example, you can see, normalize-space function is used in xpath building to strip leading and trailing white space.

No comments:

Post a Comment