测试-Selenium:是否可以在Selenium中设置WebElement的任何属性值?
我有一个WebElement,我想将其属性值重置为其他值(例如,该属性为attr,并且要将其原始value=1更改为新的value=10)。
可能吗? 我正在使用Selenium 2.0(WebDriver。)
yami asked 2020-06-24T15:05:48Z
6个解决方案
48 votes
您将必须使用JavascriptExecutor类:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
CBRRacer answered 2020-06-24T15:06:02Z
16 votes
如果您正在使用PageFactory模式或已经具有对WebElement的引用,那么您可能希望使用现有对WebElement的引用来设置属性。 (而不是在JavaScript中执行document.getElementById(...))
以下示例使您可以使用现有的WebElement引用来设置属性。
代码段
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.FindBy;
public class QuickTest {
RemoteWebDriver driver;
@FindBy(id = "foo")
private WebElement username;
public void exampleUsage(RemoteWebDriver driver) {
setAttribute(username, "attr", "10");
setAttribute(username, "value", "bar");
}
public void setAttribute(WebElement element, String attName, String attValue) {
driver.executeScript("arguments[0].setAttribute(arguments[1], arguments[2]);",
element, attName, attValue);
}
}
Nick Grealy answered 2020-06-24T15:06:32Z
10 votes
基于先前答案的花式C#扩展方法:
public static IWebElement SetAttribute(this IWebElement element, string name, string value)
{
var driver = ((IWrapsDriver)element).WrappedDriver;
var jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript("arguments[0].setAttribute(arguments[1], arguments[2]);", element, name, value);
return element;
}
用法:
driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");
Vitaliy Ulantikov answered 2020-06-24T15:06:57Z
2 votes
另一个回答这个问题的人可以在这里@nilesh回答[https://stackoverflow.com/a/19934852/2079692]
public void setAttributeValue(WebElement elem, String value){
js = (JavascriptExecutor) webDriver;
String scriptSetAttrValue = "arguments[0].setAttribute(arguments[1],arguments[2])";
js.executeScript(scriptSetAttrValue, elem, "value", value);
}
这利用了硒findElementBy函数的优势,在该函数中也可以使用xpath。
Anudeep Samaiya answered 2020-06-24T15:07:23Z
0 votes
我创建了这个jquery来解决我的问题。
public void ChangeClassIntoSelected(String name,String div) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("Array.from($(\"div." + div +" ul[name=" + name + "]\")[0].children).forEach((element, index) => {\n" +
" $(element).addClass('ui-selected');\n" +
"});");
}
使用此脚本,您可以将实际的类名更改为其他名称。
Darío Spasaro answered 2020-06-24T15:07:47Z
-1 votes
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementsByClassName('featured-heading')[0].setAttribute('style', 'background-color: green')");
我可以使用上述代码在Java中添加属性
boney dsilva answered 2020-06-24T15:08:11Z