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

使用Python Selenium点击同时满足多文本条件的div容器的方法

解决方案

你只要修改XPath定位规则,直接匹配同时满足两个子元素条件的父div即可,同时我帮你修正了原代码中超时分支会报错的问题(原代码超时的时候order变量未定义,直接调用order.text会抛异常)。

修改思路

XPath支持叠加多个过滤条件,我们可以直接定位class为order的div,同时校验两个子元素的文本规则:

  1. 后代h6标签包含dienst文本
  2. 后代p标签包含你定义的today日期文本

修改后完整代码

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
from selenium.common.exceptions import TimeoutException

# 你的driver初始化逻辑保留,这里省略
# driver = webdriver.Chrome()

today = "Nov 23"
# 组合XPath条件,同时匹配两个子元素规则
target_xpath = f"//div[contains(@class, 'order') and .//h6[contains(text(), 'dienst')] and .//p[contains(text(), '{today}')]]"

try:
    order = WebDriverWait(driver, 3).until(EC.presence_of_element_located((By.XPATH, target_xpath)))
    print(f"找到符合条件的工单,日期:{today},包含dienst关键词")
    order.click()
except TimeoutException: 
    print(f"未找到同时包含dienst关键词和日期{today}的工单")

可选优化

如果需要匹配不区分大小写的dienst(比如文本可能是Dienst、DIENST等),可以把XPath里的h6匹配规则改成大小写不敏感的写法:

.//h6[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'dienst')]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:24:06