The technique to verify if the requirements given by the user meet with the actual software product developed is known as Software Testing. Moreover, it also checks if the final software product developed is error-free or not. Software testing can either be performed manually or with the help of software testing tools. The testing which is done automatically through the inbuilt tools is known as Automation Testing. An incredible library in Python, Selenium helps you in automated testing of the software. While doing automation testing, are you not able to find an element by text in the required web page? Then, you are at an appropriate place. In this article, we will be discussing the appropriate steps along with an example to do the same.
Syntax: driver.find_element_by_xpath(“//tag [contains( text(), ‘word’)]”)
- tag: Here, tag stands for the tag name which contains the particular word.
- word: Here, word stands for the text which has to be found in a particular string. We don’t need to write a complete sentence which we want to find, but we can write a few words which are unique in the web page.
Example: For instance, consider this simple page source:
Once you have created a driver, you can grasp an element using:
button = driver.find_element_by_xpath (“//button[contains( text( ), ‘Geeks for Geeks’)]”)
Let’s understand this with implementation:
Step 1: First, import the libraries, selenium, and time.
Step 3: Next, establish a connection with the web driver through the executable path.
Step 4: Now, obtain the website in which you want to find the element.
Step 5: Then, make python sleep for few seconds so, by that time, the webpage gets loaded.
Step 6: Finally, find the desired element through text on the given web page.
Below is the full implementation:
Further, the text to be found is searched and displays the output as given below.
More locators for locating single elements:
|find_element_by_id||The first element with the id attribute value matching the location will be returned.|
|find_element_by_name||The first element with the name attribute value matching the location will be returned.|
|find_element_by_xpath||The first element with the xpath syntax matching the location will be returned.|
|find_element_by_link_text||The first element with the link text value matching the location will be returned.|
|find_element_by_partial_link_text||The first element with the partial link text value matching the location will be returned.|
|find_element_by_tag_name||The first element with the given tag name will be returned.|
|find_element_by_class_name||The first element with the matching class attribute name will be returned.|
|find_element_by_css_selector||The first element with the matching CSS selector will be returned.|
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.