Selenium等待元素出现
https://www.selenium.dev/documentation/webdriver/waits/
有时候我们需要等待网页上的元素出现后才能操作。selenium中可以使用以下几种方法等大元素。
直接time.sleep()
这个不用解释了吧....
time.sleep(秒)
隐式等待implicitly_wait
# 设置粘性超时以隐式等待找到元素或完成命令。
# 每个会话只需要调用一次此方法,针对所有元素都生效。
driver.implicitly_wait(2.5)
什么意思呢?就是你使用find_element()方法查找元素最长的等待时间,
显示等待WebDriverWait
实现该功能的核心为:WebDriverWait类
通过调用WebDriverWait 中的方法until或者until_not,并向其传递查找元素的方法。
until(method)方法:调用提供的method,直到返回值为True(也就是找到了元素)
unitl_not(method)方法:调用提供的method,直到返回值为False (也就是找不到元素...)
实际上until和until_not就是一个循环判断获取元素:看源码如下:
def until(self, method, message: str = ""):
"""Calls the method provided with the driver as an argument until the \
return value does not evaluate to ``False``.
:param method: callable(WebDriver)
:param message: optional message for :exc:`TimeoutException`
:returns: the result of the last call to `method`
:raises: :exc:`selenium.common.exceptions.TimeoutException` if timeout occurs
"""
screen = None
stacktrace = None
# 将当前时间+超时秒数,然后计算最长等待时间
end_time = time.monotonic() + self._timeout
# 死循环一直判断获取元素
while True:
try:
# 调用函数
value = method(self._driver)
# 如果有值就返回,此时就会跳出循环了
if value:
return value
except self._ignored_exceptions as exc:
screen = getattr(exc, "screen", None)
stacktrace = getattr(exc, "stacktrace", None)
# 没有找到值就sleep指定的秒数.self._poll是初始化WebDriverWait类时指定的,没有指定默认为0.5秒
time.sleep(self._poll)
# 判断当前时间是否超过了最长等待时间,超过了就跳出循环直接抛出异常!
if time.monotonic() > end_time:
break
raise TimeoutException(message, screen, stacktrace)
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
**from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC **
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
# 显式等待
WebDriverWait(driver, 20, 0.5).until(
EC.presence_of_element_located((By.LINK_TEXT, '好123'))
)
# 参数20表示最长等待20秒
# 参数0.5表示0.5秒检查一次规定的标签是否存在。默认就是0.5
# EC.presence_of_element_located((By.LINK_TEXT, '好123')) 表示通过链接文本内容定位标签
# 每0.5秒一次检查,通过链接文本内容定位标签是否存在,如果存在就向下继续执行;如果不存在,直到20秒上限就抛出异常
print(driver.find_element_by_link_text('好123').get_attribute('href'))
driver.quit()
本文来自博客园,作者:运维爱背锅,转载请注明原文链接:https://www.cnblogs.com/juelian/p/17559593.html
分类:
爬虫 / Selenium
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步