如何比较webElement列表中的值并单击列表中的所需值

时间:2017-09-14 13:51:43

标签: java selenium selenium-webdriver

我正在使用以下代码:

  public static void main(String[] args)
        {System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.17.0-win64\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.makemytrip.com/flights");
        driver.manage().timeouts().implicitlyWait(10,TimeUnit.MILLISECONDS);
            driver.manage().window().maximize();
            driver.findElement(By.id("hp-widget__sfrom")).click();
            driver.findElement(By.id("hp-widget__sfrom")).clear();
            List<WebElement> Cities = driver.findElements(By.xpath("//div[@class='autoCompleteItem']"));

    for (WebElement size1 : Cities )
    {
        String str = size1.getText(); 
            System.out.println(str);
                if(size1.getText().equals("LON"))
                {
                    size1.click();
                    break;
                }
                else
                {
                    System.out.println("match not found"); 
                }   
    }
}
}

2 个答案:

答案 0 :(得分:0)

使用以下代码:

     driver.get("https://www.makemytrip.com/flights");

     driver.findElement(By.id("hp-widget__sfrom")).click();
     driver.findElement(By.id("hp-widget__sfrom")).clear();
     try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     driver.findElement(By.id("hp-widget__sfrom")).sendKeys("LON");


     List<WebElement> Cities = driver.findElements(By.xpath("//div[@class='autoCompleteItem']//span[contains(.,'London, UK - All Airports')]"));
   for (WebElement size1 : Cities )
   {
           String str = size1.getText(); 

         if(size1.getText().equalsIgnoreCase("London, UK - All Airports"))
         {
              System.out.println(size1.getText());
             size1.click();
             break;
         }
         else
         {
             System.out.println("match not found"); 
         }   
     }
   }
}

如果您在下拉列表中的值,则需要首先关注该元素。

答案 1 :(得分:0)

如果你只想检查文本,那么你可以简单地形成一个xpath并避免这个循环。

try{
    WebElement city =driver.findElement(By.xpath("//div[@class='autoCompleteItem' and text()='LON']");
    city.click();
}catch (NoSuchElementException ex){
    System.out.print("Element not Found");
}