1

I would like to only print out items starting with i to s from a dropdown list in amazon. I have the for loop which list them all as in the code 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')]/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());
}
smac89
  • 39,374
  • 15
  • 132
  • 179
squathub
  • 33
  • 1
  • 7

2 Answers2

0

You can do it like this. Use reg ex to match strings starting from i to s . And if match found you can print it.

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()

please refer this one for more info

Sandunka Mihiran
  • 556
  • 4
  • 19
  • For some reason it prints: Prime Video Music, CDs & Vinyl Kindle Store Men's Fashion Industrial & Scientific Luggage Movies & Television Pet Supplies Software Sports & Outdoors – squathub Nov 02 '18 at 05:19
  • That is because those words are starting with uppercase. convert the string to lowercase before match. Matcher m = p.matcher(elem.getText().toLowercase().replace(" ","")); – Sandunka Mihiran Nov 02 '18 at 05:21
  • By the way these words are eliminated by the regular expression I provided. please see https://regex101.com/r/lKuEyx/1/ – Sandunka Mihiran Nov 02 '18 at 05:26
  • Still prints out the same – squathub Nov 02 '18 at 05:44
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);
    }    
}