Selenium: Iterate Through Element List

纵饮孤独 提交于 2021-02-19 03:11:12

问题


I am using XPath/CSS and Selenium to locate elements on website. I want to create a method where I iterate through a list of locators (XPath / CSS) and program chooses whichever one works. In other words, it begins with locator one - if the locator is present it returns true and exists the loop. Otherwise it moves on to the next locator in list. Once it exhausts all CSS locators it moves on to XPath and so on.

Currently, I am thinking of implementing this as follows:

public boolean iterate(WebDriver driver, By selectorType, String[] locator)
    {

        driver.get("URL");
        for(int selectorListCounter = 0; selectorListCounter < locator.length; selectorListCounter++) {

            try 
            {

                driver.findElement(By.(selectorType)).sendText();
                System.out.println("CSS Selector: " + CSS + " found");
                return true;
            } catch (Exception e)

            {
                System.out.println(CSS + " CSS Selector Not Present");
                return false;
            }


        }

I then plan on calling this method for each locator type (once for XPath, once for CSS etc)

Is this the best way?


回答1:


I actually did this yesterday just to speed up my result process. Where instead of success and failure you have Option 1 and Option 2.

The implicit wait time is 1 second per check for element in this program. So the while loop lasts 8 seconds total (as it makes two arrays per itteration). This checks for the presence of an element by putting it into an array and then checks the size of the array, it the element isn't present the array will be empty. However when one of these conditions fails it means one of your elements exits on the page.

Then below it we set booleans to find out which of these elements was present on the page and catch the error of the one that doesn't exist.

driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
int checkForElement=1;
success = false; failure = false;
        while (driver.findElements(By.className("successMessage")).size()==0 && driver.findElements(By.className("errormessage")).size()==0 && checkForElement<=4 )
        {
            checkForElement+=1;
        }
        checkForElement=1;//reset variable
        try
        {
            @SuppressWarnings("unused")//suppresses the warning so that the class is clean
            WebElement successful = driver.findElement(By.className("successMessage"));//not used practically, but logically used to look for the presence of an element without waiting the normal implicit wait time I would have at 6 seconds
            success = true;
        }
        catch(Exception e)
        {
            success = false;
        }
        try
        {
            @SuppressWarnings("unused")//suppresses the warning so that the class is clean
            WebElement failing = driver.findElement(By.className("errormessage"));//not used practically, but logically used to look for the presence of an element without waiting the normal implicit wait time I would have at 6 seconds
            failure = true;
        }
        catch(Exception e)
        {
            failure = false;
        }

        if(success)
        {
            //run success code
        }
        else if(failure)
        {
            //run failure code
        }



回答2:


I think the below solution will work for you, i dont see a need to loop around once for each type of locator. findElement() doesnt care what mechanism you use to locate an element as long as it is a valid mechanism

 //Define as many locators as you like
 private static final By cssLaunchIcon() {return By.css("div.myDemoItemActions i.launchIcon");}
 private static final By cssLaunchIcon1() {return By.css("div.myDemoItemActions i.launchIcon.a");}
 private static final By cssLaunchIcon2() {return By.css("div.myDemoItemActions i.launchIcon.li");}
 private static final By xpathLauncIcon() {return By.xpath("//ul/li/a[text()='launch']");}
 private static final By idLaunchIcon() {return By.id("launchIcon");}

 //Initialise the non empty list of locators
 List<By> locators= Arrays.asList(cssLaunchIcon(), xpathLauncIcon(), idLaunchIcon(), cssLaunchIcon1(), cssLaunchIcon2());

 public booolean findElement(List<By> locators) {
    Iterator<By> locs = locators().iterator();
    boolean found = false;
    //while iterator has another locator && no locator found yet
    while(locs.hasNext && !found) {
    WebElement el = locs.next();
    try{
      if(driver.findElement(el).isDisplayed) {
        found = true
      }
    } catch(NoSuchElementException e) {
        System.out.println("Could not find " + el)
   }
   return found;
 }


来源:https://stackoverflow.com/questions/31603764/selenium-iterate-through-element-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!