【问题标题】:How to make Selenium see invisible elements?如何让 Selenium 看到隐形元素?
【发布时间】:2017-08-24 17:08:29
【问题描述】:

Selenium 的一个问题是,当页面大量使用 AJAX 请求时,Selenium 不知道请求何时完成,因此它应该何时开始查询页面以获取请求的元素。

我解决这个问题的想法是在页面中放置一个不可见的div,其中包含一个计数器,每次 AJAX 请求完成时都会递增:

<!-- will be v1v after first AJAX requext, v2v after the second etc. -->
<div style="display: none;" id="ajaxcounter">v0v</div>

所以在 Selenium 测试代码中我可以这样写:

WebDriverWait(self.driver, 10).until(
    text_to_be_present_in_element((By.ID, "ajaxcounter"), "v1v")
)
# test stuff that depends on the first AJAX request

但是,上面的行引发了selenium.common.exceptions.TimeoutException,因为显然 Selenium 拒绝“看到”带有 style="display: none;" 的元素的内容(如果我删除了这个 display: none;,那么 Selenium 可以正常工作)。

是否有可能让 Selenium 看到这个不可见的元素?它可以正常抱怨任何其他不可见的元素,但它仍然应该只看到这一个元素。

【问题讨论】:

标签: selenium


【解决方案1】:

您可以使用“等待 ajax”之类的方法来完成。

    public void WaitForAjax(int timeoutSecs = 10)
    {
        for (var i = 0; i < timeoutSecs; i++)
        {
            var ajaxIsComplete = (bool) _browser.ExecuteScript("return jQuery.active == 0");
            if (ajaxIsComplete) return;
            Thread.Sleep(100); //retry interval
        }
    }

【讨论】:

    【解决方案2】:

    您有多种选择。我推荐这个:

    WebDriverWait(self.driver, 10).until(
        presence_of_element_located((By.XPATH, "//*[@id='ajaxcounter' and text()='v1v']"))
    )
    

    Xpath 会找到 id 为 'ajaxcounter' 且文本为 'v1v' 的元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 1970-01-01
      相关资源
      最近更新 更多