【问题标题】:Selenium 2 WebDriver - Chrome - Getting the value from a text box that is set via JavaScriptSelenium 2 WebDriver - Chrome - 从通过 JavaScript 设置的文本框中获取值
【发布时间】:2010-09-22 07:40:19
【问题描述】:

我正在使用 Selenium 2(来自 Googlecode 的最新版本),我让它启动 Chrome 并转到一个 url。

当页面加载了一些 javascript 来设置文本框的值。

我告诉它通过 id 找到一个文本框,但它没有其中的值(如果我硬编码一个值,它会找到它)。

查看 PageSource 例如Console.WriteLine(driver.PageSource);显示html,文本框为空。

我尝试过使用:

driver.FindElement(By.Id("txtBoxId") 获取元素,也不会获取值。

我也试过 ChromeWebElement cwe = new ChromeWebElement(driver, "txtBoxId"); (抱怨过时的数据)。

有什么想法吗?

约翰

【问题讨论】:

  • 似乎它检查结果的速度太快了。添加 Thread.Sleep(300);意味着检索到了结果(尽管我相信它们是一种更好的硒方法,可以调用它来表示等待结果)。

标签: c# selenium selenium-webdriver


【解决方案1】:

终于找到答案了!这是适合我的代码

WebDriverWait wait = new WebDriverWait(_driver, new TimeSpan(0,0,60));
wait.Until(driver1 => _driver.FindElement(By.Id("ctl00_Content_txtAdminFind")));
Assert.AreEqual("Home - My Housing Account", _driver.Title);

这是我的来源! http://code.google.com/p/selenium/issues/detail?id=1142

【讨论】:

    【解决方案2】:

    Selenium 2 没有为 DOM 中的元素内置的等待函数。这与 Selenium 1 中的相同。

    如果你必须等待,你可以这样做

      public string TextInABox(By by)
      {
        string valueInBox = string.Empty;
        for (int second = 0;; second++) {
          if (second >= 60) Assert.Fail("timeout");
          try
          {
            valueInBox = driver.FindElement(by).value;
            if (string.IsNullOrEmpty(valueInBox) break;
          }
          catch (WebDriverException)
          {}
          Thread.Sleep(1000);
        }
        return valueInBox;
      }
    

    或者类似的东西

    【讨论】:

      【解决方案3】:

      我通过 ruby​​ 使用 webdriver(实际上是黄瓜 watir-webdriver),我倾向于这样做:

        def retry_loop(interval = 0.2, times_to_try = 4, &block)
          begin
            return yield
          rescue
            sleep(interval)
            if (times_to_try -= 1) > 0
              retry
            end
          end
          yield
        end
      

      然后,每当由于 javascript 写入或其他原因出现内容时,我只需将其包装在 retry_loop 中,如下所示:

          retry_loop do #account for that javascript might fill out values
            assert_contain text, element
          end
      

      您会注意到,如果它已经存在,则不会有性能损失。显然,相反的情况(检查某些东西不存在)总是需要达到超时。 我喜欢在方法和测试代码中保持细节打包的方式。

      也许你可以在 C++ 中使用类似的东西?

      【讨论】:

        猜你喜欢
        • 2016-04-29
        • 2019-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-14
        • 2016-06-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多