python selenium 等待元素出现_Selenium(Python)等待元素出现

本文详细介绍了如何在Python的Selenium中进行显式和隐式等待,以确保元素出现。显式等待通过`WebDriverWait`和`expected_conditions`模块实现,如`presence_of_element_located`和`element_to_be_clickable`。隐式等待则通过设置`implicitly_wait`,在找不到元素时等待指定时间。此外,还展示了如何创建自定义等待条件来检查元素是否具有特定CSS类。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值