如何使用selenium设置“值”来输入Web元素?

问题描述 投票:0回答:3

我的代码中有一个如下所示的元素:

<input id="invoice_supplier_id" name="invoice[supplier_id]" type="hidden" value="">

我想设置它的值,所以我用它的xpath创建了一个Web元素:

 val test = driver.findElements(By.xpath("""//*[@id="invoice_supplier_id"]"""))

但现在我没有看到设置该值的选项...

java selenium xpath selenium-webdriver selenium-chromedriver
3个回答
73
投票

使用

findElement
代替
findElements

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).sendKeys("your value");

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value", "your value");

或使用JavascriptExecutor

WebElement element = driver.findElement(By.xpath("enter the xpath here")); // you can use any locator
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);

(JavascriptExecutor) driver.executeScript("document.evaluate(xpathExpresion, document, null, 9, null).singleNodeValue.innerHTML="+ DesiredText);

或(在 JavaScript 中)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")

希望对你有帮助:)


4
投票
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

编辑:显然,setAttribute() 方法对于 WebElement 类型的对象不再可用。不知道如何解决这个问题。


2
投票

正如 Shubham Jain 所说,这对我很有用:

driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"‌​, "new value");

© www.soinside.com 2019 - 2024. All rights reserved.