1. 程式人生 > >Selenium+Python測試元素等待--顯式等待、隱式等待

Selenium+Python測試元素等待--顯式等待、隱式等待

'''
元素等待
顯示等待是針對某一個元素進行相關等待判定
隱式等待不針對某一個元素進行等待,而是全域性元素等待
---------------------------------------------
WebDriverWait--顯示等待針對元素時使用
expected_conditions--預期條件類()
NoSuchElementException--用於隱式等待丟擲異常
By用於元素定位
---------------------------------------------
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
'''
#顯式等待---------------------------------------------------------------
from selenium import webdriver
from time import sleep
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("https://cn.bing.com/")
sleep(4)
driver.find_element_by_css_selector("#sb_form_q").send_keys("Python")
#顯式等待--判斷搜素按鈕是否存在
element=WebDriverWait(driver,5,0.5).until(EC.presence_of_element_located((By.CLASS_NAME,"b_searchboxSubmit")))
element.click()
sleep(4)

driver.quit()

#顯式等待---------------------------------------------------------------

​​​​​​​#隱式等待---------------------------------------------------------------

from selenium import webdriver
from time import sleep,ctime
from selenium.common.exceptions import NoSuchElementException

driver=webdriver.Firefox()
driver.get("http://www.baidu.com/")
sleep(2)

driver.implicitly_wait(2)

#檢測搜尋框是否存在
try:
    print(ctime())
    driver.find_element_by_css_selector("#sb_form_q").send_keys("Python")
    driver.find_element_by_css_selector(".b_searchboxSubmit").click()
except NoSuchElementException as msg:
    print(msg)
finally:
    print(ctime())
sleep(4)
driver.quit()

​​​​​​​#隱式等待---------------------------------------------------------------