Reputation: 831
I am trying to get the Title of 2nd page and value of textbox with id="searchCount" from 2nd page. As per the below code I am getting the Title of the 1st page and getting "org.openqa.selenium.NoSuchElementException" for element with id searchCount....which means the code is getting data from 1st page ...before the loading of 2nd page. How to fix this problem?? I am clearly clicking the searchbutton with id="fj" and loading the 2nd page...but data retrieved is from wrong page.
WebDriver driver = new FirefoxDriver(capabilities);
driver.get("https://www.indeed.co.uk");
driver.findElement(By.id("what")).sendKeys("Selenium");
driver.findElement(By.id("where")).clear();
driver.findElement(By.id("where")).sendKeys("London");
driver.findElement(By.id("fj")).click(); //loads next page
System.out.println(driver.getTitle()); //getting ist page's title here instead of 2nd page's title
System.out.println(driver.findElement(By.id("searchCount")).getText());
driver.close();
Upvotes: 2
Views: 311
Reputation: 473833
You need to wait until the title changes via WebDriverWait
and titleContains
condition:
driver.findElement(By.id("fj")).click();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("Selenium"));
System.out.println(driver.getTitle());
Note that you don't necessarily need to wait specifically for a word in a title, there are other expected conditions as well. For example, you could've also waited for search results container (td
element with id="resultsCol"
) to be present (presenceOfElementLocated
expected condition).
Or, alternatively, you can wait for the element with id="searchCount"
to be visible:
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement searchCount = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("searchCount")));
System.out.println(driver.getTitle());
System.out.println(searchCount.getText());
Upvotes: 2