How to Get Link Text in Selenium Webdriver Java
Selenium is an
open-source
web-based automation
tool that is implemented using a web driver. We will be using geckodriver
because Selenium 3
enables geckodriver as the default WebDriver implementation for
Firefox.
Pre-requisites:
- geckodriver.exe
- maven dependency selenium
<dependency> <groupid>org.seleniumhq.selenium</groupid> <artifactid>selenium-java</artifactid> <version>4.1.1</version> </dependency>
Steps:
Getting link text takes 4 simple steps:
-
Set
webdriver.gecko.driver
and its'path
as a system property. - Set the firefox diver and browse to the website.
-
Get the HTML Div containing anchor tag as Web-element using
webdriver.findElement()
function and CSS selector. - Get link text heading element and print.
Let’s see all the above steps in the code. We will use
Webelment.getText()
function to get the text of the link.
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class GetLinkText { public static String GECKODRIVER_PATH ="F:\\WORK\\SeleniumShortTasks\\LinkText\\src\\main\\resources\\geckodriver.exe"; public static void main(String[] args) { //set firefox webdriver System.setProperty("webdriver.gecko.driver", GECKODRIVER_PATH); WebDriver driver = new FirefoxDriver(); //get the firefox browser & Browse the Website for text String siteLink = "https://www.google.com.pk/search?q=java+file+not+found&sxsrf=ALiCzsaayoaw5Rv6IQgXaOa5HGmO_QFVKA%3A1659405207640&ei=l4PoYsXMJoKW9u8PtICe2A0&ved=0ahUKEwiF9MGPhqf5AhUCi_0HHTSAB9sQ4dUDCA4&uact=5&oq=java+file+not+found&gs_lcp=Cgdnd3Mtd2l6EAMyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEOgcIIxCwAxAnOgcIABBHELADOgQIIxAnOgoIABCxAxCDARBDOgQIABBDOgcIIxDqAhAnOgsIABCABBCxAxCDAToICAAQsQMQgwE6BwgAELEDEEM6BQgAEJECSgQIQRgASgQIRhgAUOAFWJkuYKAzaAJwAXgEgAG2AogB1jKSAQYyLTIyLjKYAQCgAQGwAQrIAQrAAQE&sclient=gws-wiz"; driver.get(siteLink); //Get Heading Div WebElement headingDiv = driver.findElement(By.cssSelector("div.yuRUbf")); //Get element with tag a = Link WebElement link = headingDiv.findElement(By.tagName("a")); System.out.println("Link Text = "+link.findElement(By.tagName("h3")).getText()); } }
Output:
All resources used in this tutorial are attached:
- source code
- geckdriver.exe
Comments
Post a Comment