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

如何使用Selenium Java在网页中输入文本?

你当前代码的核心问题是By.后未指定具体的元素定位规则,Selenium需要先准确定位到「Your name」对应的输入框元素,才能执行文本输入操作。

调整方案

首先在开发者工具的元素面板中,找到「Your name」对应的<input>标签,获取它的可定位属性,再补充到By类的对应方法中即可,常见定位方式示例如下:

  • 按id定位(优先级最高,仅适用于id属性唯一的场景)
    假设输入框标签为<input type="text" id="yourName" placeholder="Your name">,代码写法:
    By fieldNameYourNamePath = By.id("yourName");
    WebElement fieldNameYourName = driver.findElement(fieldNameYourNamePath);
    // 输入前先清空原有内容,避免默认值干扰
    fieldNameYourName.clear();
    fieldNameYourName.sendKeys("Test");
    
  • 按name属性定位
    假设输入框标签为<input type="text" name="username" placeholder="Your name">,代码写法:
    By fieldNameYourNamePath = By.name("username");
    WebElement fieldNameYourName = driver.findElement(fieldNameYourNamePath);
    fieldNameYourName.clear();
    fieldNameYourName.sendKeys("Test");
    
  • 按XPath定位(兼容性最高,无唯一id/name时优先使用)
    可直接在开发者工具元素面板右键对应输入框,选择「复制」-「复制XPath」获取定位路径,代码写法:
    // 引号内替换为你复制的XPath内容即可
    By fieldNameYourNamePath = By.xpath("//*[@id='yourName']");
    WebElement fieldNameYourName = driver.findElement(fieldNameYourNamePath);
    fieldNameYourName.clear();
    fieldNameYourName.sendKeys("Test");
    
  • 按CSS选择器定位
    同样可在开发者工具右键复制CSS选择器使用,写法:
    By fieldNameYourNamePath = By.cssSelector("#yourName");
    WebElement fieldNameYourName = driver.findElement(fieldNameYourNamePath);
    fieldNameYourName.clear();
    fieldNameYourName.sendKeys("Test");
    

优化提示:如果页面存在加载延迟,建议添加显式等待,避免元素未渲染完成就执行查找操作导致报错,示例如下:

import java.time.Duration;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

// 最长等待10秒,直到元素处于可点击状态
WebElement fieldNameYourName = new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.elementToBeClickable(By.id("yourName")));
fieldNameYourName.clear();
fieldNameYourName.sendKeys("Test");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:12:02