Updated September 16, 2023
Definition of Xpath Contains
Contains is an XPath function used to find Dynamic web elements and returns a partial attribute value to locate the web element. Contains function has two arguments as a String and is much preferred for a part of a value. Using its function (), we can extract all the elements on the page that match the provided text value.
Table of Contents
Syntax:
Here is the declaration of contains in Xpath:
The General format is shown as follows:
Xpath=//tagname[contains (@Attribute, 'Value')]
Using Text
[contains(text(),'XYZ')]
using id
div[contains(@id,'test')]
In Python, it has
driver.find_element_by_xpath("//tag [contains( text(), 'word')]")
Here, the tag is the tag’s name containing the specific word.
word: In this case, the word refers to the text that must be discovered in a specific string. We don’t have to enter the entire statement we’re looking for; instead, we can write a few unique words on the web page.
Let’s initiate their work, followed by an implementation.
How does XPath contains works?
The contains() function aids the user in locating elements with partial values or dynamically changing values by verifying matches with a piece of the value. contains() is a Selenium function that searches for web elements that contain a specific text within an XPath expression. The XPath function contains offers the ability to detect elements containing partial text. They are used in any condition on Xpath.
Let’s take an HTML code here:
<html>
<body>
<div id="cosmetics"><br><br><br><br><br><br><br><br><br><br><br>
<button type="button">World Wide Market</button><br><br>
<button type="button" >OLAY</button><br><br>
<button type="button">MAC </button><br><br>
<button type="button">FruitMAC</button><br><br>
<button type="button">Fruit</button><br><br>
<button type="button">Lakme MAC</button><br><br>
</div>
</body>
</html>
It can be defined as:
Xpath for the World Wide Market : //button[contains(text(),’World’)]
Xpath for the Lakme : //button[contains(text(),’Lak’)]
Let’s take More complex items: Similarly, if you use /button[contains(text(),’ Fruit’)] to discover the XPath for a fruit juice, it will also find the element with the text Fruit. If we use MAC, we might acquire a MAC element.
So, where do we look for the Fruit MAC Button?
Xpath for FruitMAC:/button[contains(text(),’Fruit’)][contains(text(),’MAC’)] is the Xpath for FruitMAC.
You can apply the function not just for the text but for other properties, e.g.: /button[contains(@type,’ but’)].
Sample Showing of the text
"//h4/a[contains(text(),'MCQ M')]"
Identifying by Attribute using XPath
When specific uniquely recognized attribute values are accessible in the container tag, we employ the XPath functions (contains or starts-with) with the attribute. The “@” symbol is used to access attributes.
By value attribute, it is given as
input[contains(@value.'Feeling')]
The output shows a single matching node. It is known that utilizing the attribute value with the contain() function and either “Feeling” or “Lucky” will uniquely identify the element. However, it is crucial to notice that the element will be appropriately identified even if we use the entire Value attribute content.
Using Class Check
//div[contains(concat(' ',normalize-space(@class),' '),' MCQ ')]
Because the “check if part of the space-separated list” operation does not exist in Xpath, the above statement is the workaround (source).
To implement in Python, the following steps should be taken:
1. Importing all the necessary libraries and time.
2. An executable path establishes a connection with the web driver efficiently.
3. obtain the respective website using a driver to find an element.get().
4. To make the web page load, turn the driver to sleep for a few seconds.
5. Lastly, the desired element is found on the web page.
Let’s see a few examples
1. multiple condition: //div[@class=’XYZ’ and contains(text(), ‘Hello’)]
2. partial match: //span[contains(text(), ‘Assign ID’)]
3. starts-with: //input[starts-with(@id,’reporterror’)]
4. value has spaces: //div[./div/div[normalize-space(.)=’More examples…’]]
5. sibling: //td[.=’LoadType’]/following-sibling::td[1]/select”
6. more complex: //td[contains(normalize-space(@class), ‘actualcell sajcell-row-lines saj-special x-grid-row-collapsed’)]
Examples of XPath contains
Below are the different examples:
Example #1
Using the text() method in Selenium, we can quickly determine the XPath of any link. Open the Google homepage at www.google.com, for example. We will generate an XPath of a Gmail link on this website. When we study it, we notice something similar to what’s shown in the screenshot below:
The text we gave here is ‘Gmail’ and the Xpath to the link is
XPath(Images): //a[contains(text(), 'Images')]
Now we shall see the screenshot like this:
Explanation:
It is evident from the preceding example that the includes() function does not require the absolute(full) text to identify the element accurately. The fragmentary text is sufficient to identify it appropriately. The selected partial text, on the other hand, should be unique. The user may easily recognize the element even if the page’s orientation changes using the contains() method.
Example #2
Code:
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 home
{
public static void main(String[] args)
{
WebDriver driv = new FirefoxDriver();
driv.manage().window().maximize();
String URL = "https://www.facebook.com";
driv.get(URL);
driv.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
WebElement searchBox = driv.findElement(By.xpath("//input[contains(@name,'q')]"));
searchBox.sendKeys("Selenium");
WebElement sButton = driv.findElement(By.xpath("//input[contains(@name,'btnK')]"));
sButton.click();
driver.close();
System.out.println("Test is done");
}
}
Explanation:
The developer creates a web driver object initially, followed by the driver. The URL’s link is placed in a variable. Calling a get() method, we pass a URL as a parameter. To load a home page, timeout has been initialized. To find an element in a search box, the findElement() function is initialized. Finally, we use the driver.close() method to end the web browser session. Therefore, we found Xpath elements using the XPath contain() function in the above code.
Output:
Example #3: Contain using Python
Code:
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.firefox(executable_path="C:\\firefoxdriver.exe")
driver.implicitly_wait(0.8)
driver.get("https://www.educba.com/about/about_blog.htm")
l = driver.find_element_by_xpath("//a[text()='Privacy Policy']")
m = driver.find_element_by_xpath("//a[contains(text(), 'Privacy')]")
print('content obtained with text(): ' + l.text)
print('content obtained with contains(): ' + m.text)
driver.quit()
Explanation:
With the Selenium web driver in Python, we may use the XPath to find an element that contains specific content. This locator includes features that aid in verifying specific text within an element. Initially, we had set a driver.exe and followed by launching a URL. The element text is retrieved using the variable, function text(), and contains(). Therefore, an Output is shown below.
Output:
Conclusion
Coming to an end, in this article, we have described appropriate working steps along with an example in selenium Xpath. Also, we covered the contain() functions, how to use them, and multiple examples in different platforms of where they are ideal.
Recommended Articles
Here, we discuss the definition and syntax; how does it work? Examples with code implementation. You may also have a look at the following articles to learn more –