如何使用 Javascriptexecutor 在没有 Id 作为定位器的元素中输入文本?

Kov*_*hta 5 javascript selenium webdriver selenium-chromedriver selenium-webdriver

我想在文本框中输入文本,该文本框不通过 SendKeys 接受输入。我继续使用 Javascriptexecutor 输入文本并成功。现在有一些字段没有可以选择作为定位器的 ID,因此我需要使用 Xpath 来定位它们。我想知道如何在 Javascriptexecutor 中通过 xpath 定位元素并将值传递给它。

JavascriptExecutor jse = (JavascriptExecutor)driver
jse.executeScript("document.getElementById('value').value='1611 
Dragons';");
Run Code Online (Sandbox Code Playgroud)

我需要一种可以使用它的方法,例如:

document.getElementByXpath("Xpath Here").value='xyz';");
Run Code Online (Sandbox Code Playgroud)

如果之前在某处记录过,请随时引导我找到文档/答案。

Sam*_*ora 4

尝试以下代码,它可以解决您的问题:

 WebElement element = driver.findElement(By.xpath("enter the xpath here"));
 JavascriptExecutor jse = (JavascriptExecutor)driver;
 jse.executeScript("arguments[0].value='enter the value here';", element);
Run Code Online (Sandbox Code Playgroud)