如何使用javascript使用SeleniumWebDriver和java设置所选web元素的属性?
我想使用javascript为网页上的选定元素设置属性 我发现了两种使用javascript设置属性的方法 一, 二, 但我想将javascript应用到使用SeleniumWebDriver发现的特定webelement如何使用javascript使用SeleniumWebDriver和java设置所选web元素的属性?,java,javascript,selenium,selenium-webdriver,Java,Javascript,Selenium,Selenium Webdriver,我想使用javascript为网页上的选定元素设置属性 我发现了两种使用javascript设置属性的方法 一, 二, 但我想将javascript应用到使用SeleniumWebDriver发现的特定webelement driver.findElement(By.linkText("Click ME")) 例如,我使用SeleniumWebDriver选择了一个链接 driver.findElement(By.linkText("Click ME")) 现在我想使用javascript设
driver.findElement(By.linkText("Click ME"))
例如,我使用SeleniumWebDriver选择了一个链接
driver.findElement(By.linkText("Click ME"))
现在我想使用javascript设置这个webelement的属性
但我不知道如何将两者结合起来
请帮助我找到解决方案大致如下:
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);
我也遇到了类似的问题,我使用了javascript执行器 所以在我的例子中,我有一个元素列表,我必须在其中更改一个属性 这里我首先查找元素,然后遍历列表,创建一个javascriptExecutor对象,然后在该特定元素上执行脚本
//arguments[0] means the element
//arguments[1] means the property
//arguments[2] means the new value of the propert
List<WebElement> unselectableDiv = driver
.findElements(By.xpath("//div[@class='x-grid3-cell-inner x-grid3-col-6']"));
for (WebElement element : unselectableDiv) {
// System.out.println( "**** Checking the size of div "+unselectableDiv.size());
JavascriptExecutor js = (JavascriptExecutor) driver;
String scriptSetAttr = "arguments[0].setAttribute(arguments[1],arguments[2])";
js.executeScript(scriptSetAttr, element, "unselectable", "off");
System.out.println(" ***** check value of Div property " + element.getAttribute("unselectable"));
}
//参数[0]表示元素
//参数[1]表示属性
//参数[2]表示属性的新值
List unselectableDiv=驱动程序
.findElements(By.xpath(“//div[@class='x-grid3-cell-inner x-grid3-col-6']”);
for(WebElement元素:unselectableDiv){
//System.out.println(“****检查div的大小”+不可选择的div.size());
JavascriptExecutor js=(JavascriptExecutor)驱动程序;
String scriptSetAttr=“arguments[0].setAttribute(参数[1],参数[2]);
executeScript(scriptSetAttr,元素,“不可选择”,“关闭”);
System.out.println(“******检查Div属性的值”+element.getAttribute(“不可选择”));
}
根据您的代码试用:
driver.findElement(By.linkText("Click ME"))
innerHTML
似乎设置为单击我
因此,要将一个新值(例如10
设置为innerHTML
),您可以使用接口的方法,并可以使用以下解决方案:
- 使用innerHTML:
元素tobelickable()
,并且可以使用以下解决方案:
- 使用文本内容:
参考文献 有关详细讨论,请参见:
driver.findElement(By.linkText("Click ME"))
WebDriver driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].setAttribute('innerHTML', '10')", element);
WebElement element = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.linkText("Click ME")))
((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('textContent','10')", element);