Python中关于selenium的expected_conditions如何使用?

程序 1: 
WebDriverWait(driver,10).until(expected_conditions.find_element_by_xpath(某路径)) 

程序 2: driver.implicitly_wait(10)
driver.find_element_by_xpath(某路径)

请问,上面程序 1 和程序 2 实现的功能是否是相同的,都是等待某个操作完成,但等待时间最长不超过 10 秒? 我理解应该实现的功能是相同的,区别在于程序 1 需要对于每一个操作都调用 expected_conditions,但是程序 2 只要写一次 implicitly_wait 语句,就可以对整个程序文件中的操作都实现同样的效果,是这样么? 感谢指点!


Python中关于selenium的expected_conditions如何使用?

2 回复

在Selenium里用expected_conditions(EC)主要是为了处理页面加载时的等待问题,让脚本更稳定。核心就两步:创建等待对象,然后用EC条件去等。

最常用的模式是配合WebDriverWait。比如等一个元素出现再点击:

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

driver = webdriver.Chrome()
driver.get("your_url")

# 最多等10秒,每0.5秒检查一次条件
wait = WebDriverWait(driver, 10, poll_frequency=0.5)

# 等id为"submit"的元素出现,然后点击
submit_btn = wait.until(EC.presence_of_element_located((By.ID, "submit")))
submit_btn.click()

几个最常用的EC条件:

  1. 等元素存在/可见

    • presence_of_element_located(locator):元素出现在DOM里就行,哪怕看不见。
    • visibility_of_element_located(locator):元素不仅要在DOM里,还得是可见的(长宽大于0,没被隐藏)。这个更常用,尤其是要操作的时候。
  2. 等元素可点击

    • element_to_be_clickable(locator):等元素可见且可点击。这是点击操作前的黄金标准。
  3. 等文本出现

    • text_to_be_present_in_element(locator, text_):等元素里出现特定文本。比如等加载完成的提示。
  4. 等页面标题/URL

    • title_contains(partial_title):等页面标题包含某个字符串。
  5. 等元素消失

    • invisibility_of_element_located(locator):等元素从DOM里消失或不可见。比如等加载动画结束。

组合使用和超时处理: until方法会等到条件满足,如果超时就抛TimeoutException。你可以用try-except来抓这个异常,处理等不到的情况。

from selenium.common.exceptions import TimeoutException

try:
    element = wait.until(EC.visibility_of_element_located((By.ID, "dynamic_content")))
    print("找到了!")
except TimeoutException:
    print("没等到元素,超时了。")

简单说,关键就是选对条件,设个合理的超时时间。


python 有个模块叫 logging,看看文档你就可以打开 DEBUG 级别的输出,然后你就能在控制台看到 selenium 和浏览器交互的完整过程,然后你就知道上面两种方法的阻塞原理了。简单来说,方法一是轮询的实现,而方法二是线程休眠的实现。

回到顶部