简体   繁体   中英

Selenium/Java exiting a while loop

I'm adding a bunch of people to a list and I want to remove them from the list later. I've written a method that clicks on a standard X element to remove the users. My problem is that when I get to a point where there are no more instances of the X element to click on I get an error as follows:

"[31morg.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//div[3]/ul/li/div/div/img"} "

But isn't that the way I'm coming out of my While loop? When the element = null and therefore the condition is false shouldn't the while loop just end and not kick out an error message?

public class PrivacyList extends FluentPage {

@FindBy(xpath="//div[3]/ul/li/div/div/img") 
private FluentWebElement XIcon ;


public void removeUserFromlist(){

    while(XIcon!= null){            
            System.out.println("XICON is displayed");
            XIcon.click();
            System.out.println("XICON was clicked");
        }
    System.out.println("Users Removed");
}

}

Thanks

PageFactory , using @FindBy , evaluates the WebElement lazily - this means first time it is used. After the first time, it is not evaluated again! So in your case, if it is found the first time, it will never become null , unless you reevaluate it every time through the loop.

You will have to use something else to exit out of your loop. Perhaps the count of the //div[3]/ul/li elements.

评估Xpath地址而不是webElement解决了这个问题,并且是一个简单的方法。

while(driver.findElements(By.xpath("//div[3]/ul/li/div/div/img")).size()!=0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM