腳本的執行速度較快,而網站響應的時間較慢。
為此,第一種方法是給腳本設置休眠時間,等待網站響應,然后腳本再執行(不推薦)
實例代碼:
# 獲取到按鈕元素,并點擊按鈕
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()