如何使用硒设置“值”以输入Web元素?

我的代码中有一个元素,看起来像这样:

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

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

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

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


答案 1

使用而不是findElementfindElements

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

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

OR using 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);

OR (在 javascript 中)

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

希望它能帮助你:)


答案 2
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

推荐