2017-08-24 116 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 
     } 
    }