2017-08-24 117 views
0

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> 

因此,在硒的测试代码,我可以把线像此:

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,因为显然硒拒绝“看到”元素的含量与style="display: none;"(如果删除这个display: none;然后SEL enium工作正常)。

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

+2

你确定这是不是与你有关的:https://stackoverflow.com/questions/2835179/how-to-get-selenium-to-wait-for-ajax-response – Adam

回答

0

您有多种选择。我建议这样的:

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

中的XPath会发现元素的id是“ajaxcounter”和文字“v1v”。

1

你可以使用类似'等待阿贾克斯'来完成。

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 
     } 
    }