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

基于兄弟元素值定位Python-Selenium元素并填充输入框问题

为指定文本的span对应的input填充值(兄弟元素关联方案)

给定HTML结构:

<div>
  <span>Title</span>
  <input value="a">
</div>
<div>
  <span>Price</span>
  <input value="">
</div>

需求:定位文本为“Price”的span对应的input,填充值“10”,且元素类名、位置均为动态生成,无法依赖静态属性定位。

方案1:XPath直接定位兄弟input

利用XPath的following-sibling轴,直接找到目标span的同级input元素,完全不依赖父元素属性:

//span[text()='Price']/following-sibling::input

以Selenium为例,执行代码:

from selenium.webdriver.common.by import By

# 定位并填充值
price_input = driver.find_element(By.XPATH, "//span[text()='Price']/following-sibling::input")
price_input.send_keys("10")

如果需要处理文本前后空格的情况,可改用normalize-space(text())='Price'做严格匹配。

方案2:通过父元素关联定位

如果页面中存在多个同级input,可先定位到span的父div,再在父元素内查找input,确保是同一容器下的元素:

//span[text()='Price']/parent::div/input

对应代码:

price_input = driver.find_element(By.XPATH, "//span[text()='Price']/parent::div/input")
price_input.send_keys("10")

方案3:CSS选择器(视工具支持情况)

利用CSS相邻兄弟选择器+,结合:contains()伪类定位:

span:contains('Price') + input

注意:原生ChromeDriver不支持:contains(),需通过JavaScript执行:

price_input = driver.execute_script("return document.querySelector('span:contains(\"Price\") + input');")
price_input.send_keys("10")

若使用jQuery,可直接执行:

$("span:contains('Price') + input").val("10");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:25:48