sleep 強制等待
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
browser = webdriver.Chrome()
browser.get("http://localhost/selenium/myForm.html")
username_input = browser.find_element(by=By.ID, value="id01")
username_input.send_keys("aaa")
time.sleep(10) # 強制停止10s
password_input = browser.find_element(by=By.NAME, value="pwd")
password_input.send_keys("123456")
implicitly_wait 隱性等待
from selenium import webdriver
browser = webdriver.Chrome()
browser.implicitly_wait(3) # 最長等待時間
browser.get("http://localhost/selenium/myForm.html")
WebDriverWait 顯性等待
一般結(jié)合until()或者until_not()和expected_conditions類使用
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
browser = webdriver.Chrome() # 創(chuàng)建瀏覽器對象
browser.get("http://localhost/selenium/myForm.html")
timer = WebDriverWait(driver=browser, timeout=3) # 生成WebDriverWait對象,設(shè)置超時時間
ec_obj = EC.presence_of_element_located(locator=(By.XPATH, '//*[@id="id_sub123"]')) # 生成ec對象,判斷元素是否被加到了 dom 樹里
try:
sub_btn = timer.until(ec_obj) # 嘗試等待元素出現(xiàn)
except NoSuchElementException:
browser.save_screenshot(filename='./Screenshots/error_useTimer.png') # 元素不存在時截圖
except TimeoutException:
browser.save_screenshot(filename='./Screenshots/error_timeout.png') # 超時時截圖
else:
sub_btn.click()
browser.back()
finally:
pass
expected_conditions的常用方法
| 方法 | 說明 |
|---|---|
| title_is | 判斷當前頁面的 title 是否完全等于(==)預(yù)期字符串,返回布爾值 |
| title_contains | 判斷當前頁面的 title 是否包含預(yù)期字符串,返回布爾值 |
| presence_of_element_located | 判斷元素是否被加到了 dom 樹里(注意,加載到dom樹中,并不代表這個元素可見) |
| presence_of_all_elements_located | 判斷是否至少有 1 個元素存在于 dom 樹中。舉例:如果頁面上有 n 個元素的 class 都是’wp’,那么只要有 1 個元素存在,這個方法就返回 True |
| visibility_of_element_located | 判斷元素是否可見 |
| visibility_of | 同visibility_of_element_located方法,只是visibility_of_element_located方法參數(shù)為locator,這個方法參數(shù)是 定位后的元素 |
| text_to_be_present_in_element | 判斷某個元素中的 text 是否 包含 了預(yù)期的字符串 |
| text_to_be_present_in_element_value | 判斷某個元素中的 value 屬性是否包含 了預(yù)期的字符串 |
| frame_to_be_available_and_switch_to_it | 判斷該 frame 是否可以 switch進去,如果可以的話,返回 True 并且 switch 進去,否則返回 False |
| invisibility_of_element_located | 判斷某個元素中是否不存在于dom樹或不可見 |
| element_to_be_clickable | 判斷某個元素中是否可見并且可點擊 |
| staleness_of | 等某個元素從 dom 樹中移除,返回 True或 False |
| element_to_be_selected | 判斷某個元素是否被選中了,一般用在下拉列表 |
| element_selection_state_to_be | 判斷某個元素的選中狀態(tài)是否符合預(yù)期 |
| element_located_selection_state_to_be | 跟上面的方法作用一樣,只是上面的方法傳入定位到的 element,而這個方法傳入 locator |
| alert_is_present | 判斷頁面上是否存在 alert |