Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in DevOps and Agile by (19.7k points)

I'm trying to get text using selenium web driver and here is my code. Please note that I don't want to use Xpath, because in my case, id gets changed on every re-launch of the web page,kindly help with this!

my code:

text=driver.find_element_by_class_name("current-stage").getText("my text")

HTML:

<span class="current-text" id="yui_3_7_0_4_1389185744113_384">my text</span>

1 Answer

0 votes
by (62.9k points)

In Python, you can do:

element = driver.find_element_by_class_name("class_name").text

This will return your text and verify it after that. In Java, you can do:

Also, we've to use the above Class locator in the Selenium WebDriver Command which is used to retrieve the text in the specified Heading text element.

_driver.findElement(By.className("Class LOCATOR")).getText( );

  is the syntax we've to use to retrieve the text from the specified locator.

 Lets understand the _driver.findElement(By.className("Class Locator")).getText( );   syntax by breaking it as below:

  • _driver - is the WebDriver object 

  • findElement( )  - is used for locating the elements on which we have to perform the operations

  • By.className("Class LOCATOR") - By.className informs the findElement( ) to find the elements using Class LOCATOR

  • Locator - is the actual locator we want to find (i.e. some text )

  • getText( ) - is the WebDriver command which can also be used to retrieve the text from the specified locator

The result of this statement is a string text. In order to store the retrieved text, we have to create a String object and assign the result of the above statement to the retrieved string text.

String heading_text = _driver.findElement(By.className("Class Locator").getText( );

To learn in-depth about Selenium, sign up for an industry based Selenium certification

Wanna become an Expert in python? Come & join our Python Certification course

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...