Friday 9 June 2017

Selenium WebDriver : Getting text from Web Page

If you want to get some text (full / partial) that is displayed on Web Page, for verification, data extraction or any other purpose, we have some WebDriver methods that will do the job for us. Users with basic Object-Oriented knowledge can easily use these methods to achieve what is required.

In Types of Locators, we have seen different techniques to locate Web Page elements that are required to be found during Test Automation. It includes finding by ID, ClassName, Tag, LinkText, etc. that can be achieved by using appropriate Selenium WebDriver methods using the WebDriver Object instance.

In this post, we are going to see the way of extracting text from Web Page using Selenium WebDriver. Trust me it is as simple as one line of code.
Check the following code snippet :



public class Sample {
public static void main(String[] args) {
//Initialize Browser
System.setProperty("webdriver.gecko.driver", "E:\\AllJARS\\Selenium_Driver_Servers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/");

//Find element
WebElement element = driver.findElement(By.cssSelector("a[href='https://mail.google.com/mail/?tab=wm']"));

//Get Text
System.out.println(element.getText());
}
}


The above code snippet navigates to Google, finds link (Gmail), extracts the text (Gmail) and prints it on console.

getText() method is used to extract the text from the Web Page element found using one of the locating techniques.
In this way we can find the required element and get or extract the required text from the Web Page. Further, we can use any substring() method provided by Java to get the desired String value (reduced length compared to Original String).


element.getText();

So, the above line of code can be used to extract the text from Web Page as required. Simple, isn't it ?
Hope you liked this post. In case of any queries or suggestions, feel free to comment in comments section.
Thank you for reading.

Happy Learning.

YouTube Channel : Click Here

No comments:

Post a Comment