我只想从亚马逊的下拉列表中打印以 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/