java WebElement 的 setAttribute() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35136773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:47:22  来源:igfitidea点击:

setAttribute() method for WebElement

javac#pythonseleniumselenium-webdriver

提问by Guy

In this questionboth answers used setAttribute()as WebElementfunctionality. However, I couldn't find this method in the Java, C#nor Pythondocumentation, only getAttribute(). Trying to call this method from WebElementobject in C# (Visual Studio) and Java (Eclipse) with the latest Seleniumversion produced the same results.

这个问题的两个答案用setAttribute()WebElement功能。但是,我在JavaC#Python文档中都找不到这种方法,只有getAttribute(). 尝试从WebElement最新Selenium版本的C# (Visual Studio) 和 Java (Eclipse) 中的对象调用此方法产生了相同的结果。

So my question is, does this method really exist?

所以我的问题是,这种方法真的存在吗?

回答by alecxe

After inspecting the selenium Python API docsand the source code, I can conclude - there is no such a method. And, there is nothing about it inside the WebDriver specificationitself.

在检查了 selenium Python API 文档源代码后,我可以得出结论 - 没有这样的方法。而且,在WebDriver 规范本身中没有任何关于它的内容。

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")

回答by AlexCharizamhard

They are using the JavascriptExecutor class.

他们正在使用 JavascriptExecutor 类。

I.e.

IE

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);
}