我从Selenium Java中的下拉菜单中排序项目列表

时间:2018-11-02 04:23:09

标签: java selenium-webdriver

我只想从亚马逊的下拉列表中打印以i到s开头的项目。我有一个for循环,将它们全部列出,如下面的代码所示:

driver = new ChromeDriver();
driver.get("https://www.amazon.com");

Actions actions = new Actions(driver);
WebElement ele = driver.findElement(By.xpath("//span[@class='nav-line-2' and contains(.,'Departments')]"));

Thread.sleep(300);
actions.moveToElement(ele);
actions.perform();


WebDriverWait wait = new WebDriverWait(driver, 10);
//List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@id='nav-flyout-shopAll']/div[contains(@class, 'nav-tpl-itemList')]/a")));
List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@id='nav-flyout-shopAll']/div[contains(@class,'nav-tpl-itemList')]//span")));
int itemsCount = elements.size();
System.out.println(itemsCount);

for(WebElement elem: elements) {
    System.out.println(elem.getText());
}

2 个答案:

答案 0 :(得分:0)

您可以这样做。使用reg ex匹配从i到s的字符串。如果找到匹配项,则可以打印出来。

Pattern p = Pattern.compile("^[i-s]+");


for(WebElement elem: elements) {
     Matcher m = p.matcher(elem.getText());
     if (m.find()){
      System.out.println(elem.getText());
     }     
 }

Regex doesn't work in String.matches()

请参阅此以获得更多信息

答案 1 :(得分:0)

Simplest solution i can think is below.

driver = new ChromeDriver();
driver.get("https://www.amazon.com");

Actions actions = new Actions(driver);
WebElement ele = driver.findElement(By.xpath("//span[@class='nav-line-2' and contains(.,'Departments')]"));

Thread.sleep(300);
actions.moveToElement(ele);
actions.perform();


WebDriverWait wait = new WebDriverWait(driver, 10);
List<WebElement> elements = wait.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//div[@id='nav-flyout-shopAll']/div[contains(@class,'nav-tpl-itemList')]//span")));
int itemsCount = elements.size();
System.out.println(itemsCount);

for(WebElement elem: elements) {
    Strng text = elem.getText();
    if(!text.matches("(i|j|k|l|m|n|o|p|q|r|s).*"))
    {
      System.out.println(text);
    }    
}