AJAX 載入的清單可能會為 Selenium 中的可見性驗證帶來挑戰。要可靠地檢查包含多個元素的清單是否已完全加載,請考慮以下方法:
使用WebDriverWait,您可以引發visibility_of_all_elements_ located() 條件:
<code class="python">elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.ltr li[id^='t_b_'] > a[id^='t_a_'][href]")))</code>
或者,您可以使用XPath:
<code class="python">elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")))</code>
要等待特定數量的元素,例如10,請使用lambda 函數:
<code class="python">myLength = 9 WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) > int(myLength))</code>
<code class="python">myLength = 10 WebDriverWait(driver, 20).until(lambda driver: len(driver.find_elements_by_xpath("//ul[@class='ltr']//li[starts-with(@id, 't_b_')]/a[starts-with(@id, 't_a_') and starts-with(., 'Category')]")) == int(myLength))</code>
以上是如何使用Python有效地等待Selenium中多個元素的載入?的詳細內容。更多資訊請關注PHP中文網其他相關文章!