Selenium:我可以在Selenium中设置WebElement的任何属性值吗?

yam*_*ami 47 testing selenium

我有一个WebElement,我想将其属性的值重置为其他值(例如attr属性,我想将其原始值更改value=1为new value=10).

可能吗?我正在使用Selenium 2.0(WebDriver.)

CBR*_*cer 48

您必须使用JavascriptExecutor类:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('//id of element').setAttribute('attr', '10')");
Run Code Online (Sandbox Code Playgroud)

  • 您好,感谢您的回复,但在 Sel2.0 中我们无法获取文档对象引用。我们必须通过WebDriver获取元素,它返回不支持属性设置的“WebElement”。driver.findElement(By.id("元素的id')) (2认同)
  • Quickquestion:有没有办法在webelement的上下文中执行javascript?换句话说:拥有一个`WebElement`(例如:一个简单的`<span>`没有其他属性)有一种方法可以执行javascript并以某种方式传递对这个js元素的引用.(也许在js中`this`会引用它?) (2认同)
  • 找到答案:将`WebElement(s)`传递给执行者,并在脚本中访问`arguments [0]([1,2 ...])`. (2认同)

Nic*_*aly 17

如果您正在使用PageFactory模式或已经具有对WebElement的引用,那么您可能希望使用对WebElement的现有引用来设置该属性.(而不是document.getElementById(...)在你的JavaScript中做)

以下示例允许您使用现有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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Vit*_*kov 10

基于以前答案的花式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;
}
Run Code Online (Sandbox Code Playgroud)

用法:

driver.FindElement(By.Id("some_option")).SetAttribute("selected", "selected");
Run Code Online (Sandbox Code Playgroud)


Anu*_*iya 5

另一个回答这个问题的人可以在这里回答@nilesh /sf/answers/1395439671/

public void setAttributeValue(WebElement elem, String value){
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("arguments[0].setAttribute(arguments[1],arguments[2])",
        elem, "value", value
    );
}
Run Code Online (Sandbox Code Playgroud)

这利用了 selenium findElementBy 函数,其中也可以使用 xpath。