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()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容