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")
- python selenium中等待元素出现及等待元素消失操作
- 初学者的Selenium自动化测试指南,基于Python(六)——如何设置元素等待
- 自动化测试——Selenium+Python判断元素是否可见,及元素未出现时设置超时时限
- selenium设置元素发现超时等待时间-python
- python里三种等待元素出现的方法
- [Selenium]怎样等待元素出现之后再消失,譬如Loading icon
- python使用selenium获取元素出现错误:"errorMessage":"Compoud class names not permitted"
- selenium 等待特定元素出现
- selenium python 编码格式 页面元素显式、隐式等待 鼠标悬浮
- [Selenium]等待元素出现之后再消失,界面上的loading icon都属于这种类型,之前的方法总是卡死,换这种方法目前还好用的
- Python appium selenium当页面元素 没有加载出来时 ,等待元素加载出来的方法
- Selenium with Python 008 - WebDriver 元素等待
- python selenium等待特定网页元素加载完毕
- Selenium等待元素的处理方法
- Selenium:元素等待的4种方法
- python统计数组元素出现次数以及排序
- Selenium with Python 004 - 页面元素操作
- python+selenium安装过程出现ImportError: No module named selenium问题
- python+selenium 定位元素异常类型及解决方法
- selenium + python之元素定位