setAttribute() method for WebElement
23,678
Solution 1
After inspecting the selenium Python API docs and the source code, I can conclude - there is no such a method. And, there is nothing about it inside the WebDriver specification itself.
To set an attribute, usually a script is executed:
elm = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].setAttribute(arguments[1], arguments[2]);",
elm,
"attr_name",
"attr_value")
Solution 2
They are using the JavascriptExecutor class.
I.e.
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
Or an Extension Method
public static void setAttribute(this IWebElement element, string value, bool clearFirst)
{
if (clearFirst) element.Clear();
element.SendKeys(value);
}
Author by
Guy
Updated on February 02, 2020Comments
-
Guy over 4 years
In this question both answers used
setAttribute()
asWebElement
functionality. However, I couldn't find this method in the Java, C# nor Python documentation, onlygetAttribute()
. Trying to call this method fromWebElement
object in C# (Visual Studio) and Java (Eclipse) with the latestSelenium
version produced the same results.So my question is, does this method really exist?
-
Guy over 8 yearsNo they are not, they are using this
driver.findElement(By.xpath("//input[@id="invoice_supplier_id"])).setAttribute("value", "your value")
-
Guy over 8 yearsI agree, I couldn't find it either. But two different people gave this answer so I started wondering...
-
alecxe over 8 years@guy yeah, I suspect these people are simply wrong. But, good finding.
-
Guy over 8 yearsNothing I could find.
-
AlexCharizamhard over 8 yearsI mean you could easily create an extension method that executes the javascript via the xpath or Id or sendkeys to the element. Look at what I editted with.
-
Guy over 8 yearsYes, you could easily create this method. However, they didn't show JavaScript implementation, they used it as
WebElement
method. They chained this method todriver.findElement()
, which returnWebElement
. -
AlexCharizamhard over 8 yearsWhich is why I am led to believe that it is similar to the extension method I posted.
-
AlexCharizamhard over 8 yearsIf you really want to be able to set the properties of your htmlcontrols .NET's CodedUI Framework allows you to access them and change them.
-
Guy over 8 yearsI will look into it. But they didn't mention any changes in the html controls, they simply called the method as it was part of
WebElement
API. -
Hiep Tran about 6 yearsThank you, it take me a lot of try, about 5 hour, and this line help me out