首页 > 解决方案 > 如果找不到元素则继续,如果找到则保存它

问题描述

我有一个循环,我一个一个打开链接。在这个循环中,我有 if 语句,它检查:

  1. 如果我看到名字,然后我复制它
  2. 如果我没有看到名字,那么我会忽略它并继续循环。

    List<WebElement> demovar = driver.findElements(By.xpath("//*[@id=\"big_icon_view\"]/ul/li/p/a"));
    System.out.println(demovar.size());
    ArrayList<String> hrefs = new ArrayList<String>(); 
    for (WebElement var : demovar) {
        System.out.println(var.getText());
        System.out.println(var.getAttribute("href"));
        hrefs.add(var.getAttribute("href"));
    }
    
    int i = 0;
    for (String href : hrefs) {
        driver.navigate().to(href);
        System.out.println((++i) + ": navigated to URL with href: " + href);
        if(driver.findElement(By.xpath("//a[@id='name']")).isDisplayed()) {
            System.out.println("I can see Name");
        } else {
            System.out.println("I cant see Name");
        }
        Thread.sleep(3000); // To check if the navigation is happening properly.
    }
    

为什么这不能正常工作?正如我所假设的,它应该具有以下内容:

  1. 如果显示元素,那么我可以看到名称
  2. 否则不显示元素,然后我看不到名称。

标签: javaselenium

解决方案


我不确定您在此处看到什么错误消息,但如果您的代码不起作用,那么很可能该元素没有显示在页面上,因此您在尝试定位它时会收到异常。

您可以捕获NoSuchElementException以处理元素未出现在页面上的情况。

 for (String href : hrefs) {
    driver.navigate().to(href);
    System.out.println((++i) + ": navigated to URL with href: " + href);
    // create isDisplayed variable
    boolean isDisplayed = true;
    try {
        isDisplayed = driver.findElement(By.xpath("//a[@id='name']")).isDisplayed();
        }
    catch(NoSuchElementException) {
            isDisplayed = false;
        }
        // do something else here with isDisplayed
        if (isDisplayed) { System.out.println("I can see Name"); }
        else { System.out.println("I can not see Name"); }
}

这段代码做的事情几乎和你的一样,但是NoSuchElementException如果元素没有出现在页面上,我们会捕捉到被抛出的内容。

如果这对您不起作用,请随时发布您在代码中看到的错误消息或结果,这将有助于追查问题。


推荐阅读