EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials XML Tutorial XPath contains
Secondary Sidebar
Web Services Interview Questions

Spring framework Interview Questions

Orphaned Case Java

Elasticsearch Interview Questions

HTML5 Interview Questions

Big Data Books

XPath contains

XPath contains

Definition of XPath contains

Xpath Contains is an XPath function that is 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 the XPath contains() function, we can extract all the elements on the page that match the provided text value.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Here is the declaration of contains in Xpath:

The General format is shown as:

Xpath=//tagname[contains (@Attribute, ‘Value’)]

Using Text

[contains(text(),'XYZ')]

using id

div[contains(@id,'test')]

In python XPath contains has

driver.find_element_by_xpath(“//tag [contains( text(), ‘word’)]”)

Here, tag: tag is the name of the tag that contains 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 words that are unique on the web page.
Let’s get started with their working 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.
Lets 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>

The XPATH contains 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.

Not just for the text you can apply contains function for other properties as well Eg: /button[contains(@type,’ but’)].
Sample Showing Xpath contains text

"//h4/a[contains(text(),'MCQ M')]"

Identifying by Attribute using Xpath

When there are certain uniquely recognised attribute values accessible in the container tag, we employ the XPath functions (contains or starts-with) with 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. It is crucial to notice, however, that even if we use the entire Value attribute content, the element will be appropriately identified.

1

Using Class Check

//div[contains(concat(' ',normalize-space(@class),' '),' MCQ ')]

Because the “check if part of space-separated list” operation does not exist in Xpath, the above statement is the workaround (source).

To implement in Python following steps should be taken:

1. Importing all the necessary libraries and time.
2. Through an executable path, connection with the web driver is established efficiently.
3. Next to find an element -obtain the respective website using driver. get().
4. To make the web page load turning the driver to sleep for few secs.
5. Lastly, the desired element is found on the web page.

Lets see 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’)]

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, notice something similar to what’s shown in the screenshot below:

xpath
The text we gave here is the ‘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 accurately identify the element. The fragmentary text is sufficient to appropriately identify it. The selected partial text, on the other hand, should be unique. Even if the page’s orientation is changed using the contains() method, the user may easily recognize the element.

Example #2

home.py
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

Initially, a web driver object is created with the driver following it the URL’s link is placed in a variable. calling a get() method we pass an URL as a parameter. To load a home page timeout is been initialized. To find an element in a search box findElement() function is initialized. Finally, we use the driver.close() method to end the web browser session. Therefore in the above code, we found Xpath elements by using XPath contain() function.

Output:

example 2

Example #3: Contain using python

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 the verification of specific text within an element. Initially we had set a driver.exe and followed by launching an URL. The element text is retrieved using the variable along with the function text() and contains(). Therefore an Output is shown as below.

Output:

xpath contains

Conclusion

Coming to an end, in this article, we have described appropriate working steps along with an example in selenium Xpath. Also, we covered what the contain() functions are, how to use them, and multiple examples in different platforms of where they are ideal.

Recommended Articles

This is a guide to XPath contains. Here we discuss the definition, syntax, How does XPath contains works? examples with code implementation. You may also have a look at the following articles to learn more –

  1. XPath Expressions
  2. XPath Relative
  3. XPath Axes
  4. XPath Nodes
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more