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中文网其他相关文章!