其他分享
首页 > 其他分享> > selenium三大切换,三大等待

selenium三大切换,三大等待

作者:互联网

三大等待

强制等待

time.sleep()  # 使用time模块强制进行等待,单位s

 

隐式等待

driver.implicitly_wait(30) # 等待元素直到超时报异常

显式等待

# 第一步:创建一个等待计时器对象
wait = WebDriverWait(driver, 30, 0.5)
# 第二步:元素的定位方式以及定位表达式
located = ("xpath", "//a[text()='新闻']")
# 第三步:设置等待的条件
conditions = EC.visibility_of_element_located(located)
# 第四步
wait.until(conditions)

wait = WebDriverWait(driver, 30, 0.5)
located = ('id', 'su')
conditions = EC.visibility_of_element_located(located)
wait.until(conditions)

# 将选择器的方式,改成BY模块
wait = WebDriverWait(driver, 30, 0.5)
located = (By.XPATH, "//a[text()='新闻']")
conditions = EC.visibility_of_element_located(located)
wait.until(conditions)

工作中常见用法如下

WebDriverWait(driver,30,0.5).until(
    EC.visbility_of_elemnet_located((By.XPATH,"定位信息"))
)

显示等待的等待条件,应用场景  

element_to_be_clickable:等待元素处于可点击的状态
visibility_of_element_located:等待元素处于可见状态
presence_of_element_located:等待元素被加载(html中能找到这个元素)

整理一下用到的包和常规的简写

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

三大切换

iframe

1,切换iframe,通过iframe名字

driver.switch_to.frame('login_frame')
driver.find_element_by_xpath("//a[text()='帐号密码登录']").click()

2,通过索引去切换

driver.switch_to.frame(0)

3,通过元素节点去切换

ele_iframe = driver.find_element_by_xpath('//iframe[@id="login_frame"]')
driver.switch_to.frame(ele_iframe)
driver.find_element_by_xpath("//a[text()='帐号密码登录']").click()

4,使用显示等待方法连用

WebDriverWait(driver, 20, 1).until(
    EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[@id="login_frame"]'))
)
driver.find_element_by_xpath("//a[text()='帐号密码登录']").click()

5,从iframe中切换回默认的页面

driver.switch_to.default_content()

6,切换回父级的iframe中

driver.switch_to.parent_frame()

alert

# 关于alert弹框的切换
alert = driver.switch_to.alert
# 点击确认
alert.accept()
# 点击取消
alert.dismiss()
alert.send_keys("python34567890")  # 对可输入的弹框进行输入
alert.accept()

window

获得当前窗口句柄

driver.current_window_handle

获得所有窗口句柄

driver.window_handles

切换到目标句柄窗口

driver.switch_to.window(窗口名)

搭配wait方法等待新窗口打开

WebDriverWait(driver,5,0.5).until(
        EC.new_window_is_opened(start_window)
    )

标签:selenium,driver,element,located,切换,iframe,等待,三大,wait
来源: https://www.cnblogs.com/addicated/p/13194354.html