HyperLinks in HTML useful to navigate to another web-page.
HyperLinks are defined using the tag name-a using an attribute name href.
We need to define the Link text between the tag name to get the text displayed on the web-page.
Clicking on the link redirected to a new window or in the same window. This can be defined using an attribute target.
- target=_self -> opens the web-page in the same window
- target=_blank -> opens the web-page in a new window
Using Locators in Selenium WebDriver, we can automate the steps to click on the link to navigate to a page defined under the attribute href as defined below:
Link_Text
href =”http://total-qa.com” target=”_blank”
Scenario:
Is there any way to identify the broken links using Selenium WebDriver?
The below logic helps in identifying the broken links.
Currently we are using WebDriverManager to instantiate the Driver Instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
package org.totalqa; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class BrokenLinks { public static void main(String[] args) throws IOException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("http://www.total-qa.com/"); List<WebElement> links = driver.findElements(By.tagName("a")); for(int i=0; i<links.size(); i++) { WebElement element = links.get(i); String url=element.getAttribute("href"); URL link = new URL(url); HttpURLConnection con =(HttpURLConnection)link.openConnection(); System.out.println(con.getResponseCode()); if(con.getResponseCode()!= 200) { System.out.println("Response Code for Broken Link" +con.getResponseCode() ); System.out.println("Broken Link :: " + con.getURL()); } else { System.out.println("Link is working fine :: " + con.getURL()); } } } } |
Conclusion:
Broken links in a web-page are identified using Selenium and Java API.