我正在使用此功能登录页面:
public static void login() {
driver.get(url);
driver.findElement(By.name("username")).clear();
driver.findElement(By.name("username")).sendKeys("username- login");
driver.findElement(By.name("password")).clear();
driver.findElement(By.name("password")).sendKeys("password");
driver.findElement(By.name("submit")).click();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
登录成功,现在我想通过检查登录页面上的某些元素来验证这一点,如下所示:
public static void testLogin(WebDriver driver) {
String pageSource = driver.getPageSource();
//Assert.assertTrue("Login was not successful!", pageSource.contains("Welcome to the page!"));
System.out.println(pageSource);
一切正常,除了当我在控制台上显示源代码时,它是登录页面的源代码(以前的 url),因此 Assert 返回 false。
谁能指出我正确的方向?
最佳答案
您可以等待一段时间,直到新页面打开:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[contains(.,'Welcome to the page!')]")));
这应该允许您等到新页面中包含文本值 'Welcome to the page!'
的元素出现在 DOM
或者您可以等到页面标题更改:
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.titleContains("New page title"));
关于java - Selenium:getPageSource() 返回前一页的来源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41743457/