driver.getTitle()从错误页面

时间:2017-02-23 19:26:22

标签: javascript java jquery selenium

我正在尝试从第2页获取第2页的标题和带有id =“searchCount”的文本框的值。根据下面的代码,我得到第一页的标题,并获取id为searchCount ....的元素的“org.openqa.selenium.NoSuchElementException”,这意味着代码从第一页获取数据...在加载之前第2页。如何解决这个问题?我清楚地点击id =“fj”的搜索按钮并加载第二页......但是检索到的数据来自错误页面。

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

1 个答案:

答案 0 :(得分:2)

您需要通过WebDriverWaittitleContains条件等待标题更改

driver.findElement(By.id("fj")).click();

WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.titleContains("Selenium"));

System.out.println(driver.getTitle());

请注意,您不一定需要专门等待标题中的单词,还有其他预期条件。例如,您还可以等待搜索结果容器(td元素与id="resultsCol")存在(presenceOfElementLocated预期条件)。

或者,您也可以等待id="searchCount"的元素可见:

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