如何使用Selenium设置输入网页元素的“value”?

50

我代码中有一个元素长这样:

<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
如果您正在使用ID,则应使用适当的By-Locator:By.id(“invoice_supplier_id”) - Peter Wippermann
1
您目前正在收集WebElement列表。您需要从列表中提取WebElement,或者仅查找WebElement本身。在Selenium可以与其交互之前,您还需要取消隐藏该元素。 - Ardesco
3个回答

72

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

OR (在JavaScript中)

driver.findElement(By.xpath("//input[@id='invoice_supplier_id'])).setAttribute("value", "your value")
希望它能对你有所帮助 :)

2
发送按键到隐藏元素? - Kim Homann
18
我在这里遇到了相同的问题。但是WebElement中没有setAttribute方法。还有其他建议吗? - Narayan Subedi
1
@NarayanSubedi,sendKeys方法对我有效。driver.findElement(By.id("elementId")).sendKeys("value", "new value"); - eeadev
2
尝试使用send_keys代替sendKeys。 - wadhwa94
有人对这种方法有问题的话,可以尝试访问 https://sqa.stackexchange.com/questions/3387/set-attribute-of-an-element-using-webdriver-python - unholy_me
你必须在最新版本中使用以下代码:driver.find_element_by_id("invoice_supplier_id").send_keys("your value") - silent_27

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

4
findElement() 返回一个 WebElementWebElement 没有 setAttribute() 方法。 - Nathan
@Nathan,element.setattr__("value", "your value")怎么样? - Kymo Wang

2

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接