您的位置:首页 > 编程语言 > Python开发

Selenium(Python)等待元素出现

2018-03-14 22:07 771 查看

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")

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: