【问题标题】:How to set "value" to input web element using selenium?如何设置“值”以使用 selenium 输入 Web 元素?
【发布时间】:2016-05-09 16:50:59
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 如果您使用 ID,则应使用适当的 By-Locator:By.id("invoice_supplier_id")
  • 您当前正在收集 WebElement 列表。您将需要从列表中提取 WebElement,或者只查找 WebElement 本身。您还需要在 Selenium 与之交互之前取消隐藏元素。

标签: java selenium xpath selenium-webdriver selenium-chromedriver


【解决方案1】:

使用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")

希望对你有帮助:)

【讨论】:

  • 向隐藏元素发送密钥?
  • 我在这里遇到了同样的问题。但是 WebElement 中没有这样的setAttribute 方法。还有其他建议吗?
  • @NarayanSubedi,sendKeys 方法对我有用 driver.findElement(By.id("elementId")).sendKeys("value", "new value");
  • 尝试使用 send_keys 代替 sendKeys
  • 对此方法有问题的朋友可以试试sqa.stackexchange.com/questions/3387/…
【解决方案2】:
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");

【讨论】:

    【解决方案3】:

    正如 Shubham Jain 所说,这对我有用:driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"‌​, "new value");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 2013-11-23
      • 1970-01-01
      • 2015-12-02
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多