tiankele0 2020-06-26
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
driver.switch_to.frame(‘login_frame‘) driver.find_element_by_xpath("//a[text()=‘帐号密码登录‘]").click()
driver.switch_to.frame(0)
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()
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()
driver.switch_to.default_content()
driver.switch_to.parent_frame()
# 关于alert弹框的切换 alert = driver.switch_to.alert # 点击确认 alert.accept() # 点击取消 alert.dismiss() alert.send_keys("python34567890") # 对可输入的弹框进行输入 alert.accept()
driver.current_window_handle
driver.window_handles
driver.switch_to.window(窗口名)
WebDriverWait(driver,5,0.5).until( EC.new_window_is_opened(start_window) )