Monday, October 10, 2016

How to copy link address or URL from a link in selenium webdriver


Think of a scenario where you have a link in your email or a webpage and you need to see the location where it redirects to.

Refer to below piece of HTML code:
<h3><a href="https://www.google.com" >Google Link</a></h3>

In webpage, the link name is "Google Link" and clicking on it redirects user to "https://www.google.com".

Now task is to copy the link address in a variable using Java in selenium webdriver.

Refer to below selenium webdriver code for solution:
String hyperlink = driver.findElement(By.xpath("//a[text()='Google Link']")).getAttribute("href");
System.out.println(hyperlink);

Printing the value of variable hyperlink will print "https://www.google.com" in console. Please remember to verify that your locator path is correct as per your webpage code.

If you still face any issue in running the code, write to me in comments section.