selenium常見元素操作之三大等待


from selenium import webdriver
import time

#瀏覽器會話的開始
driver = webdriver.Chrome()
#driver.implicitly_wait(30) #添加全局等待時間
driver.get(“http://www.baidu.com”) #get函數默認等待靜態頁面加載完成
driver.find_element_by_xpath(’//div[@id=“u1”]//a[@name=“tj_login”]’).click() #點擊登錄按鈕
#當操作引起界面發生變化的時候,一定要加等待

三種等待

方式一:強制等待 sleep(秒)

time.sleep(5)

方式二:智能等待(隱形等待) implicitly_wait 設置全局等待時間,只需要添加一次,添加在打開瀏覽器之前

#driver.implicitly_wait(30) #設置等待最大時間30秒,超過30秒報錯TimeoutException,30秒之內何時出現何時進入下一步操作

方式三:智能等待(顯性等待) 明確的條件(元素出現,窗口打開等…) 等待+條件

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

WebDriverWait類:顯性等待類

#WebDriverWait(driver,等待時常,輪循週期).until() /until_not()

expected_conditions模塊:提供一系列希望發生的條件(有很多方法,可根據需要學習,舉例如下)

#1.元素存在:html裏面存在,能找到
#EC.presence_of_element_located
#2.元素可見:存在並且可見,有大小
#EC.visibility_of_element_located
#3.元素可用:存在-可見-並可用(只讀\不可點擊等爲不可用)
#EC.element_to_be_clickable

#等待條件表達
#step1: locator = (定位類型,定位表達式) #定位到做斷言的元素
locator = (By.ID,‘TANGRAM__PSP_11__footerULoginBtn’)
#等待元素可見
#step2: EC.visibility_of_element_located(locator) #判斷條件,元素可見
WebDriverWait(driver,30).until(EC.visibility_of_element_located(locator))
#step3:輔助等待 0.5s
time.sleep(0.5)
driver.find_element_by_id(“TANGRAM__PSP_11__footerULoginBtn”).click() #點擊用戶名登錄

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章