2

In the code below , I am expecting to see the size as 18 but it displays 0. I have not been able to figure out why.

I am going to Amazon searching for books and ultimately want to store the book titles in a array. Thanks !

@Test
public void searchTestOne(){
    System.setProperty("webdriver.gecko.driver", "C:\\geckodriver\\geckodriver.exe");
    WebDriver driver = new FirefoxDriver();
    driver.get("http://www.amazon.in");
    driver.manage().window().maximize();        

    driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Books");
    driver.findElement(By.className("nav-input")).click();

    List<WebElement> result = driver.findElements(By.xpath(".//*[@id='atfResults']/ul[@id='s-results-list-atf']/li"));

    System.out.println(result.size());
mrfreester
  • 1,981
  • 2
  • 17
  • 36
vijaya
  • 25
  • 1
  • 5

1 Answers1

0

The page is dynamic, meaning once selenium thinks the page is loaded, the content isn't actually on the page yet. So you have to wait for the results first.

In this case, You can wait until you expect more than one result since the list should all load at once:

WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
//Note this isn't giving you the titles, it's giving you the entire list item
By bookSearchResults = By.xpath(".//*[@id='atfResults']/ul[@id='s-results-list-atf']/li");

wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(bookSearchResults, 1));

//Then continue on as you were
List<WebElement> result = driver.findElements(bookSearchResults);
....

You could also just try waiting for the results div instead.

mrfreester
  • 1,981
  • 2
  • 17
  • 36
  • I notice wait condition does not wait until all the elements are loaded because the condition is search result = 1. I changed the wait to like 5 sec then all the elements loaded . just wanted to tell.. – vijaya Apr 07 '17 at 03:42
  • @vijaya interesting. I would have thought all the results would load at the same time, good catch :) One thing to note, the timeout you set won't necessarily wait that long, but it will wait up to that amount of time for the condition you set, in this case `ExpectedConditions.numberOfElementsTo...`. If you want to wait for more elements to load you would do that as the 2nd parameter in `numberOfElementsToBeMoreThan(elementsBy, amountOfElements)`. If you feel like this was a correct answer, feel free to upvote and/or mark it as the correct answer with the checkmark. Cheers! – mrfreester Apr 07 '17 at 14:31