如何删除列表中的项目,为空?

时间:2015-09-23 13:18:13

标签: java list selenium selenium-webdriver

我想从网页上获取所有链接,点击它们并检查它们是否正常工作,但我想从我的列表中删除包含null和注销的URL,因为nullpointerexception和驱动程序注销网页。你怎么能建议我这样做?请记住,我是java的新手。

这是我到目前为止的代码:

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]);  
     }

}

1 个答案:

答案 0 :(得分:1)

您可以首先避免使用不含href属性的链接

替换:

List<WebElement> alllinks = driver.findElements(By.tagName("a"));

使用:

List<WebElement> alllinks = driver.findElements(By.cssSelector("a[href]"));

过滤掉“注销”链接:

a[href]:not([href$=LogOff])