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

如何使用Selenium查找网页中含特定文本的所有input输入元素

解决方案

以下是不同场景下的实现方法:

1. 浏览器原生JavaScript实现

适合在控制台直接操作、编写油猴脚本的场景:

  • 自定义匹配规则筛选所有含目标关键词的input元素,支持匹配id、name、placeholder、class等常见属性,示例以匹配关键词email为例:
const targetKeyword = 'email';
const allInputs = document.getElementsByTagName('input');
// 筛选匹配元素,默认不区分大小写,可按需调整
const matchedInputs = Array.from(allInputs).filter(input => {
  return [input.id, input.name, input.placeholder, input.className].some(attr => 
    attr?.toLowerCase().includes(targetKeyword.toLowerCase())
  )
});

// 批量向匹配元素输入文本
matchedInputs.forEach(input => {
  input.value = '你需要输入的文本内容';
  // 可选:触发input事件,适配有表单事件监听的页面
  input.dispatchEvent(new Event('input', { bubbles: true }));
});

2. Selenium实现(以Python为例)

自动化测试场景下使用,核心是改用复数查找方法获取全部匹配元素:

  • 注意不要用单数的find_element,要用find_elements才能返回所有符合条件的元素列表:
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.missyempire.com/customer/account/create/")

target_keyword = "email"
# 构造XPath模糊匹配规则,可按需增删需要匹配的属性
xpath = f"//input[contains(@name, '{target_keyword}') or contains(@id, '{target_keyword}') or contains(@placeholder, '{target_keyword}')]"
# 获取所有匹配元素
matched_inputs = driver.find_elements(By.XPATH, xpath)

# 批量输入文本
for input_ele in matched_inputs:
    input_ele.clear()
    input_ele.send_keys("test@example.com")

3. 注意事项

  • 如果不需要给隐藏元素赋值,可以在筛选规则中新增可见性判断:Selenium场景加input_ele.is_displayed(),JS场景加!input.hidden
  • 若需要区分关键词大小写,删掉对应代码中toLowerCase()相关逻辑即可
  • 所有单元素查找方法(如JS的querySelector、Selenium的find_element)只会返回第一个匹配结果,要获取全部元素必须使用对应的复数查找方法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:06:04