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

Python Selenium如何忽略文本可变数字定位下拉框元素?

稳定定位可变文本元素的几种方案

针对括号内数字变化导致XPath失效的问题,以下几种方法可以实现稳定定位:

方法1:使用starts-with匹配固定前缀

利用文本的固定开头部分匹配,只要span文本以固定前缀开头即可,忽略后续可变的数字部分:

prioVersandOption = elem(
    '//span[starts-with(text(), "Deutsche Post Brief Prio 2,55€ & 3,70€ (")]/parent::div',
    driver)
driver.execute_script("arguments[0].click();", prioVersandOption)

方法2:组合contains匹配前后固定文本

同时匹配文本的固定前缀和后缀,确保元素文本包含这两部分,中间的数字不影响定位:

prioVersandOption = elem(
    '//span[contains(text(), "Deutsche Post Brief Prio 2,55€ & 3,70€ (") and contains(text(), " Angebote)")]/parent::div',
    driver)
driver.execute_script("arguments[0].click();", prioVersandOption)

方法3:截取文本固定长度匹配

通过substring截取文本的固定长度部分,和已知固定文本对比,完全匹配即可:

prioVersandOption = elem(
    '//span[substring(text(), 1, string-length("Deutsche Post Brief Prio 2,55€ & 3,70€ (")) = "Deutsche Post Brief Prio 2,55€ & 3,70€ (")]/parent::div',
    driver)
driver.execute_script("arguments[0].click();", prioVersandOption)

方法4:直接定位关联的输入框(如果适用)

如果该下拉选项对应的输入框value属性就是目标文本,也可以先定位输入框,再关联到对应的选项元素(需根据页面结构调整):

# 假设输入框的value包含固定前缀,先定位输入框
input_elem = driver.find_element(By.XPATH, '//input[starts-with(@value, "Deutsche Post Brief Prio 2,55€ & 3,70€ (")]')
# 再找到对应的下拉选项(需根据页面父子/兄弟关系调整XPath)
prioVersandOption = input_elem.find_element(By.XPATH, '../div[contains(@class, "option")]')
driver.execute_script("arguments[0].click();", prioVersandOption)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:12:13