我想从网页上获取所有链接,单击它们并检查它们是否正常工作,但是由于nullpointerexception和驱动程序已从网页注销,我想从列表中删除URL中包含null和注销的链接。你怎么可以建议我这样做?请记住,我是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]);
     }

}

最佳答案

您可以首先避免使用没有href属性的链接。

更换:

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


与:

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


过滤掉“注销”链接:

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

09-26 07:01