java - I-s 对 selenium java 中的下拉菜单中的项目列表进行排序

标签 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());
}

最佳答案

你可以这样做。使用 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()

请参阅此内容以获取更多信息

关于java - I-s 对 selenium java 中的下拉菜单中的项目列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53112645/

相关文章:

java - SOAP 消息生成器

java - 无法从浏览器打开文档文件

Python Selenium 超时移至循环中的下一项

html - 无法使用 XPath 按索引查找元素

selenium-webdriver - 发送 key 后,Selenium WebElement 值为空

java - 将 Adob​​e Flash 播放器嵌入到基于 Java 的桌面应用程序中

java - 在Java桌面应用程序中安全存储数据库密码的位置

java - 将字符串中数组中的所有单词替换为另一个数组中相同位置的单词

selenium - TestNG 测试没有按照优先级执行

java - 如何使用 pom.xml 在单个类中执行测试?