Reputation: 325
I want to get all links from webpage, click them and check if they are working, but i want to remove the one's with URL containing null and logoff from my list because of the nullpointerexception and driver logging off from webpage. How can you suggest me to do that? Keep in mind that I am new to java.
Here is my code that I've got so far:
private static String[] links = null;
private static int linksCount = 0;
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("webpage that I'm trying to test");
driver.manage().window().maximize();
driver.findElement(By.id("UserNameOrEmail")).sendKeys("username");
driver.findElement(By.id("Password")).sendKeys("password");
driver.findElement(By.xpath(".//*[@id='main']/form/div[3]/input")).click();
driver.findElement(By.xpath(".//*[@id='content-main']/div/div/a[3]/h3")).click();
List<WebElement> alllinks = driver.findElements(By.tagName("a"));
linksCount = alllinks.size();
System.out.println("Number of links: "+linksCount);
links= new String[linksCount];
//remove items from list (null, logoff... )
// print all the links
System.out.println("List of links Available: ");
for(int i=0;i<linksCount;i++)
{
links[i] = alllinks.get(i).getAttribute("href");
System.out.println(alllinks.get(i).getAttribute("href"));
}
// click on each link
for(int i=0;i<linksCount;i++)
{
driver.navigate().to(links[i]);
System.out.println("Link "+links[i]);
}
}
Upvotes: 1
Views: 1276
Reputation: 473853
You can avoid having links without href
attribute in the first place.
Replace:
List<WebElement> alllinks = driver.findElements(By.tagName("a"));
with:
List<WebElement> alllinks = driver.findElements(By.cssSelector("a[href]"));
To filter out the "log off" link:
a[href]:not([href$=LogOff])
Upvotes: 1