Selenium(Python)等待元素出現


1、顯式等待

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()

除非在10秒內發現元素返回,
否則在拋出TimeoutException之前等待10秒,
WebDriverWait默認每500毫秒調用一次ExpectedCondition,
直到它成功返回,
ExpectedCondition的成功返回類型是布爾值,
對於所有其他ExpectedCondition類型,
返回true或非null返回值。

預期條件,
自動化網頁瀏覽器時經常使用一些常見條件:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))


下面列出每個的名稱:

title_is
title_contains
presence_of_element_located
visibility_of_element_located
visibility_of
presence_of_all_elements_located
text_to_be_present_in_element
text_to_be_present_in_element_value
frame_to_be_available_and_switch_to_it
invisibility_of_element_located
element_to_be_clickable
staleness_of
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be
alert_is_present

自定義等待條件:

如果以上的便利方法都不符合你的要求,
您還可以創建自定義等待條件,
可以使用具有__call__方法的類創建自定義等待條件,
該條件在條件不匹配時返回False。

class element_has_css_class(object):
"""期望檢查某個元素是否具有特定CSS類
locator-用於查找元素

返回WebElement一旦它具有特定的CSS類
"""
def __init__(self, locator, css_class):
self.locator = locator
self.css_class = css_class

def __call__(self, driver):
element = driver.find_element(*self.locator)
# 查找引用的元素
if self.css_class in element.get_attribute("class"):
return element
else:
return False

wait = WebDriverWait(driver, 10)
element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass"))
# 等到ID = "myNewInput"元素有類"myCSSClass"

 


2、隱式等待

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM