MainMenu

Home Core Java Overview Maven Tutorials

Saturday, 14 January 2017

Selenium Code to verify links on Webpage

Hello friends,
Below code will verify all the links of the webpage.
When this code will start its execution then it will ask you the URL.
Enter the valid URL & after that this will give you all the links details.

package links;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class VerifyLink
{
WebDriver driver;
List yourlink;
String userurl;
@SuppressWarnings("resource")
@BeforeTest
public void f()
{
Scanner obj = new Scanner(System.in);
System.out.println("Enter Your website URL to test including http");
String userurl = obj.next();
driver = new FirefoxDriver();
driver.navigate().to(userurl);
driver.manage().window().maximize();
List yourlink = driver.findElements(By.tagName("a"));
System.out.println("Total links are :" + yourlink.size());
}
@Test
public void g() throws Exception
{
for(int i = 0; i<yourlink.size(); i++)
{
WebElement element = yourlink.get(i);
String alllinks = element.getAttribute("href");
try
{
h(alllinks);
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
public void h(String alllinks) throws Exception
{
try
{
URL testlink = new URL(alllinks);
HttpURLConnection httpurlconnect = (HttpURLConnection)testlink.openConnection();
httpurlconnect.setConnectTimeout(4000);
httpurlconnect.connect();
if(httpurlconnect.getResponseCode()==200)
{
System.out.println(testlink +"--"+httpurlconnect.getResponseMessage());
}
if(httpurlconnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND)
{
System.out.println(testlink + "--" + httpurlconnect.getResponseMessage() + "--" +HttpURLConnection.HTTP_NOT_FOUND);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

Tags :TestNG code to verify links, code to test all links

No comments:

Post a Comment