Selenium設置隱式等待時間

  • 腳本的執行速度較快,而網站響應的時間較慢。

  • 為此,第一種方法是給腳本設置休眠時間,等待網站響應,然后腳本再執行(不推薦)
    實例代碼:

# 獲取到按鈕元素,并點擊按鈕
btn = wd.find_element(By.ID,'go')
btn.click()

# 等待1秒鐘
import time
time.sleep(1)

# 通過id獲取到文本,然后打印該文本
textCode = wd.find_element(By.ID,'1')
print(textCode.text)

input()
  • 第二種方法是加入隱式等待時間的代碼 wd.implicitly_wait(秒鐘數)
    實例代碼:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# 打開瀏覽器
wd = webdriver.Chrome(service=Service(r"E:\chromedriver_win32\chromedriver"))
# 設置隱式等待時間秒鐘數
wd.implicitly_wait(10)

# 打開網頁
wd.get("https://www.byhy.net/_files/stock1.html")

key = wd.find_element(By.ID,"kw")
key.send_keys('通訊')

# 獲取到按鈕元素,并點擊按鈕
btn = wd.find_element(By.ID,'go')
btn.click()

# 通過id獲取到文本,然后打印該文本
textCode = wd.find_element(By.ID,'1')
print(textCode.text)

input()
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容