You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Selenium显式等待使用问题求助(非Java相关)

解决Selenium显式等待(除title_is外)的运行问题

嘿,我能看出你已经在Selenium显式等待上做了不少尝试,其实问题就出在两个容易忽略的小细节上,咱们一步步来修正:

问题1:缺少By类的导入

你在代码里用到了By.ID来指定定位策略,但没有导入对应的类,这会直接导致语法错误。需要在开头加上:

from selenium.webdriver.common.by import By

问题2:presence_of_element_located的参数格式错误

这个预期条件不接受直接调用By.ID('als'),它要求传入一个元组,格式是(定位策略, 定位值)。也就是说,你得把By.ID('als')改成(By.ID, 'als')——By.ID是一个代表定位策略的常量,不是可调用的函数。

修正后的完整代码

from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By  # 新增的导入

driver = webdriver.Firefox()
driver.get('https://www.google.com')

# 尝试获取<div id="als">
def presence_of_element(driver, timeout=3):
    try:
        w = WebDriverWait(driver, timeout)
        # 这里改成元组格式的定位器
        w.until(EC.presence_of_element_located((By.ID, 'als')))
        return True
    except:
        return False

print(presence_of_element(driver))

额外提示

其实不只是presence_of_element_located,Selenium里大多数需要定位元素的预期条件(比如visibility_of_element_located、element_to_be_clickable等),都要求传入这种(定位策略, 定位值)的元组格式。你的title_is能正常运行,是因为它只需要接收字符串类型的标题,不需要定位器,所以没遇到这个问题。

内容的提问来源于stack exchange,提问作者doingmybest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:24:57