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

Selenium中如何通过字段名定位CSS选择器值动态变化的元素

实现方案

Selenium没有直接通过字段文本提取对应CSS选择器的内置API,你可以通过「先定位标题节点→锁定共同父容器→父容器内查找输入框」的逻辑解决动态序号问题,完全不需要依赖可变的div:nth-child参数:

操作步骤

  • 用XPath的文本匹配能力定位到「Local Access Settings」标题元素,不受节点序号影响
  • 拿到该标题元素的父节点,也就是你原来CSS选择器里那个动态序号的div容器
  • 在已锁定的父容器范围内查找对应的http输入框即可

代码示例

如果使用Selenium 4+版本,代码如下:

from selenium.webdriver.common.by import By

# 定位Local Access Settings标题节点
title_node = self.driver.find_element(By.XPATH, "//div[contains(@class, 'section-title') and contains(text(), 'Local Access Settings')]")
# 获取标题对应的父容器(动态序号的div节点)
section_container = title_node.find_element(By.XPATH, "./parent::div")
# 在当前容器内查找http输入框,直接使用去掉动态前缀的CSS选择器即可
http_input = section_container.find_element(By.CSS_SELECTOR, "div.row > div:nth-child(1) > div > div.col-8.formik-custom-field > div > input[type=text]")
# 填充输入值
http_input.send_keys("需要输入的内容")

如果使用Selenium 3及更早版本,调整定位写法即可:

# 定位Local Access Settings标题节点
title_node = self.driver.find_element_by_xpath("//div[contains(@class, 'section-title') and contains(text(), 'Local Access Settings')]")
# 获取标题对应的父容器
section_container = title_node.find_element_by_xpath("./parent::div")
# 查找输入框
http_input = section_container.find_element_by_css_selector("div.row > div:nth-child(1) > div > div.col-8.formik-custom-field > div > input[type=text]")
http_input.send_keys("需要输入的内容")

优化提示

如果后续输入框的div:nth-child(1)也可能变动,可以继续通过输入框关联的label文本做XPath相对定位,稳定性会更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 22:09:01