You need to enable JavaScript to run this app. Python中Selenium如何基于已有WebElement使用相对XPath的显式等待
优惠活动
大模型
产品
解决方案
定价
更多

Python中Selenium如何基于已有WebElement使用相对XPath的显式等待

问题根因

  • 等待逻辑里的XPath写法错误:/h2/a 为全局绝对路径,会从页面根节点开始检索元素,不会限制在当前eachArticle元素范围内查找,自然找不到对应元素抛出异常。你直接定位时用的.//h2/a才是相对当前元素的正确路径,./前缀表示从当前节点开始检索,//表示匹配当前节点下所有层级的后代元素。
  • 另外你注释掉的presence_of_element_located用法错误:这个条件接收的是定位器元组,不是已经查找好的WebElement对象,所以之前注释的写法也是错误的。

正确实现方案

方案1:修正lambda写法

from selenium.webdriver.support.ui import WebDriverWait

all_articles = driver.find_elements_by_xpath("/html/body/div[1]/div[2]/div/div/div[1]/div/div[@class='jobs posts-loop ']/div[2]/div/article")

for index , eachArticle in enumerate(all_articles):
    try:
        # 修正XPath为相对路径,x就是传入的eachArticle元素
        WebDriverWait(eachArticle, 3).until(lambda x : x.find_element_by_xpath(".//h2/a"))
        # 等待完成后再执行后续操作
        op_link = eachArticle.find_element_by_xpath(".//h2/a").get_attribute("href")
    except Exception as ttt:
        exception_log.exception(ttt)

方案2:使用官方预期条件(更稳定,推荐)

配合presence_of_element_located,传入相对定位器即可,逻辑更简洁不易出错:

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

all_articles = driver.find_elements_by_xpath("/html/body/div[1]/div[2]/div/div/div[1]/div/div[@class='jobs posts-loop ']/div[2]/div/article")

for index , eachArticle in enumerate(all_articles):
    try:
        # 基于当前元素等待相对路径元素存在
        WebDriverWait(eachArticle, 3).until(
            EC.presence_of_element_located((By.XPATH, ".//h2/a"))
        )
        op_link = eachArticle.find_element(By.XPATH, ".//h2/a").get_attribute("href")
    except Exception as ttt:
        exception_log.exception(ttt)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 21:06:03