【问题标题】:Selenium WebDriver won't return correct title of Google results pageSelenium WebDriver 不会返回正确的 Google 结果页面标题
【发布时间】:2016-06-20 13:24:34
【问题描述】:

我正在练习 Cucumber 自动化框架,因此我可以将它用于工作项目。我正在使用 Selenium WebDriver 与浏览器进行交互。现在,我只是在测试 Google 搜索是否确实返回了正确的结果。我的功能文件在这里:

Feature: Google

    Scenario: Google search
        Given I am on the Google home page
        When I search for "horse"
        Then the results should relate to "horse"

这是我的带有步骤定义的 Java 类:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.junit.Assert;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

public class StepDefinitions {

    WebDriver driver = null;

    @Given("^I am on the Google home page$")
        public void i_am_on_the_Google_home_page() throws Throwable {
        driver = new FirefoxDriver();
        driver.get("https://www.google.com");
    }

    @When("^I search for \"([^\"]*)\"$")
    public void i_search_for(String query) throws Throwable {
        driver.findElement(By.name("q")).sendKeys(query);
        driver.findElement(By.name("btnG")).click();
    }

    @Then("^the results should relate to \"([^\"]*)\"$")
    public void the_results_should_relate_to(String result) throws Throwable {
        System.out.println(driver.getTitle());
        Assert.assertTrue(driver.getTitle().contains(result));
    }
 }

为了测试它确实返回了相关结果,我只是断言页面标题包含搜索查询。现在,最后一步失败了,因为 driver.getTitle() 返回的是“Google”,而不是预期的“horse - Google Search”。

我不确定它为什么这样做。我检查了结果页面的 HTML,标题是我所期望的。但是 Selenium 没有返回正确的结果。有人可以向我解释为什么以及如何解决它吗?

【问题讨论】:

  • 是返回上一页的标题吗?它可能在页面转换完成之前返回页面标题。抱歉,我不知道 Cucumber,所以我无法提供代码,但您可以尝试插入等待,看看是否能解决问题。

标签: java selenium junit cucumber


【解决方案1】:

答案:

可能您需要在断言页面标题之前添加一些等待时间,因为有时驱动程序操作非常快,这可能会导致断言失败

@Then("^the results should relate to \"([^\"]*)\"$")
    public void the_results_should_relate_to(String result) throws Throwable {
        WebDriverWait wait = new WebDriverWait(driver, 10);
        WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("some element in page"))));
        System.out.println(driver.getTitle());
        Assert.assertTrue(driver.getTitle().contains(result));
    }

【讨论】:

  • .implicitlyWait() 并没有像您认为的那样做。该行设置了一个全局等待时间......它不会仅在那个位置等待长达 10 秒。 seleniumhq.org/docs/04_webdriver_advanced.jsp#implicit-waits.
  • 我对 Cucumber 不熟悉,但在 Java/C# 中,您想要的是 WebDriverWait。我在 Cucumber 中找到了一个引用可能解决方案的页面。 seleniumframework.com/cucumber-jvm-3/waits-and-synchronization
  • 我已经更新了我的答案.. 我的意思是在断言页面标题之前给一些等待时间
  • WebDriverWait 是执行此操作的正确方法......我会删除 Thread.sleep() 选项,因为这不是一个好习惯。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 2017-12-27
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2012-04-11
  • 2016-02-06
相关资源
最近更新 更多