XPath Contains Text | XPath Starts With, Ends With
XPath axes in selenium are methods to identify those dynamic elements which are not possible to find by normal XPath method such as ID, Classname, Name, etc.
Axes are so named because they tell about the axis on which elements are lying relative to an element. Dynamic web elements are those elements on the webpage whose attributes dynamically change on refresh or any other operations.
The commonly useful XPath axes methods used in Selenium WebDriver are child, parent, ancestor, sibling, preceding, self, etc.
XPath axes help to find elements based on the element’s relationship with another element in a document. We will learn all methods of XPath axes with examples in the next tutorial.
How to Handle Complex and Dynamic Elements in Selenium using XPath?
There are following ways by which we can handle complex and dynamic elements in selenium. They are as follows:
- Basic XPath
- XPath Contains
- XPath Starts-with
- XPath Ends-with
- Using “OR” Statement
- Using “AND” Statement
- XPath Text
Let’s understand each way one by one to handle complex and dynamic elements in Selenium.
Basic XPath
Basic XPath expression selects nodes or list of nodes on the basis of attribute like ID, Name, Classname, etc. from XML document. For example:
XPath = //input[@name = 'user-message'] Where, input ➡ tagname name ➡ attribute user-message ➡ value of attribute.
Let’s find XPath of different elements on Facebook for practice.
Open the Facebook page https://www.facebook.com and find the XPath of email and password elements. Hope that you know the technique of finding XPath in the Chrome browser.
If not, go to this link first to learn: How to Find XPath in Chrome Browser
1. Right-click on email box and go to inspect option. Now press ctrl+F. Write XPath by following basic syntax and on the basis of the below screenshot.
We will start to write XPath with //, followed by input tag, then we will use the select attribute, followed by its attribute name like name, id, etc, and then we will choose a value of attribute in single quotes.
XPath(email): //input[@id = 'email'] (1 of 1 matched)
Here, (1 of 1) means exact match. It indicates that there is only one element available for this XPath.
If it is showing (1 of 2) or (1 of 3) and so on. In this case, you don’t need to choose this XPath because there are multiple elements available with the same XPath.
Key point:
If you find more than one element matching the same XPath, do not choose that XPath. Try to write another XPath for that element and find one matched only (i.e. 1 of 1).
XPath Contains
Contains() is a method which is used to find the value of those attribute which changes dynamically. For example, login information. Contains() method has the following general form which is given below:
Syntax: XPath: //tagname[contains(@attribute, 'value')]
For example:
We will try to find XPath of “Sign up button” on the Facebook web page for the demo. Open Facebook page, right-click on sign up button and go to inspect option.
Now write XPath in the panel like this:
XPath(Sign Up): //button[contains(@name, 'websubmit')]
Key points:
1. The main feature of contains() method is that it can find elements with partial text. For example, let’s find the same XPath for sign up button with partial text.
XPath(Sign Up): //button[contains(@name, 'web')]
In this expression, we have taken “name” as an attribute and “web” as partial text in the place of websubmit.
[adinserter block=”2″]
2. Contains() method can be used in any condition when you need to find XPath.
Similarly,
XPath(Female Radio button): //input[contains(@id, 'u_0_8')] XPath(New password): //input[contains(@id, 'u_0_13')]
Let’s automate a scenario in which we will find elements by using contains XPath.
Scenario to Automate:
1. Launch the Firefox browser by creating WebDriver object.
2. Open Google Home page https://www.google.com.
3. Send the text into the search box.
4. Click on the search button.
5. Close the browser.
Let’s write the program code to automate the following scenario.
Program code 1:
package seleniumProject;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class GoogleHomePage {
public static void main(String[] args)
{
// Creates an object of the FirefoxDriver class and assigns it to the WebDriver interface.
WebDriver driver = new FirefoxDriver();
// Maximize the Firefox browser.
driver.manage().window().maximize();
// Store the home page URL in a variable URL of type string.
String URL = "https://www.google.com";
// Call get() method using reference variable driver and pass URL as parameter to get method.
driver.get(URL);
// Wait for load home page completely.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Find element "search box" by using findElement() method of WebElement.
WebElement searchBox = driver.findElement(By.xpath("//input[contains(@name,'q')]"));
// Send a text into search box.
searchBox.sendKeys("Selenium");
// Click on the search button.
WebElement sButton = driver.findElement(By.xpath("//input[contains(@name,'btnK')]"));
sButton.click();
// Close the browser.
driver.close();
System.out.println("Test successful");
}
}
Output: Test successful
In the above program code, we have found out XPath of elements by using the contains method.
XPath Starts-with
starts-with() is a method that finds those elements whose attribute value changes on refresh on the web page. This method checks the starting text of an attribute and finds elements whose attribute changes dynamically.
We can also use this method to find elements whose attribute value is static (not changing). The general syntax for starts-with() method is given below:
Syntax: XPath: //tagname[starts-with(@attribute, 'value')]
For example, we will find XPath of search button and keyword using starts-with() method on web page https://neilpatel.com/ubersuggest.
1. XPath(Search button): //span[starts-with(@class, 'field-submit-text')] 2. XPath(Keyword): //input[starts-with(@name, 'keyword')]
Let’s automate a scenario where we will find XPath by using starts-with method.
Scenario to Automate:
1. Invoke the Firefox browser by creating a WebDriver object.
2. Open the web page URL https://www.neilpatel.com/ubersuggest
3. Send a text into the search box.
4. Click on the search button.
5. Close the browser.
Let’s write the program code to automate this scenario. Look at the program code below to understand better.
Program code 2:
package seleniumProject;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class StartswithExample {
public static void main(String[] args)
{
// Creates an object of the FirefoxDriver class by assigning it to the WebDriver interface.
WebDriver driver = new FirefoxDriver();
// Maximize the Firefox browser.
driver.manage().window().maximize();
// Store the home page URL in a variable URL of type String.
String URL = "https://www.neilpatel.com/ubersuggest";
// Call get() method using reference variable driver and pass URL as parameter to get method.
driver.get(URL);
// Wait for load home page completely.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Find element "search box" by using findElement() method of WebElement.
WebElement searchBox = driver.findElement(By.xpath("//input[starts-with(@name, 'keyword')]"));
// Send a text into search box.
searchBox.sendKeys("Selenium WebDriver");
// Click on search button WebElement.
searchButton = driver.findElement(By.xpath("//button[starts-with(@type,'submit')]"));
searchButton.click();
// Close the browser.
driver.close();
System.out.println("Test successful");
}
}
Output: Test successful
XPath Ends-with
ends-with() method checks the ending text of an attribute and finds elements whose attribute changes dynamically on refresh. It has the following syntax as follows:
Syntax: XPath: //tagname[ends-with(@attribute, 'value')]
For example, if the ID of an element is a_1_password, it will find and return elements with _password at the end of ID.
Using “OR” Statement
In OR expression, two conditions are used and anyone condition either 1st condition or 2nd condition should be true to find element. It has the following general form.
Syntax: XPath: //tagname[XPath statement-1 or XPath statement-2]
For example, we will find the XPath of login button on the Facebook page.
XPath(login button): //input[@value = 'Log In' or @type = 'submit']
In the above XPath expression, both XPath statements are true.
Using “AND” Statement
In AND expression, two conditions are used and both conditions must be true to find element. If anyone’s condition is false then XPath will be failed to find the element. It has the following general form.
Syntax: XPath: //tagname[XPath statement-1 and XPath statement-2]
For example, we will find the XPath of sign up button on the Facebook page.
XPath(Sign Up button): //button[@type = 'submit' and @id = 'u_0_19'] (1 of 1 matched).
XPath Text
The text() method is used to find elements with an exact match. The syntax for the text() method is given below:
Syntax: XPath: //tagname[text() = 'text_value']
For example, we will create XPath of text “Create a new account” on the Facebook page using text() method.
XPath(Create a new account): //div[text() = 'Create a new account'] where div is tagname. Similarly, XPath(Recent logins): //div[text() = 'Recent logins']
How to Create XPath of Link in Selenium?
We can easily determine XPath of any link in Selenium using text() method. For example, open the Google home page www.google.com.
In this webpage, we will create XPath of Gmail link. When you will inspect it, you will see like this in the below screenshot:
Here, Gmail is text. So, let’s find XPath for this link.
XPath(Gmail): //a[text() = 'Gmail']
We can also write the same XPath using contains() method like this:
XPath(Gmail): //a[contains(text(), 'Gmail')] (1 of 1 matched) Similarly, XPath(Images): //a[contains(text(), 'Images')] (1 of 1 matched)
In this tutorial, you have learned how to handle dynamic elements in selenium with the help of various examples. I hope that you will have understood XPath contains, starts-with, ends-with, OR, AND statement, text. Stay tuned with the next tutorial where you will understand iframe in Selenium.
Thanks for reading!!!