GetAttribute of WebElement in Selenium Firefox Driver Returns Empty

大兔子大兔子 提交于 2019-12-08 10:02:56

问题


So I have a test that was written, and the test runs and works using the Selenium ChromeDriver just fine. I was tasked with getting the tests working on the FirefoxDriver as well.

Part of the test we input text into a login field, and then check the login field to make sure it was input. The way we check the field is like this

public virtual string Text => WebElement.GetAttribute("value");
while (!Text.Equals(inputText) && count++ < 3)

This works perfectly fine in Chrome. However it does not in Firefox. When I debug the test, it shows that Text is "" or empty/blank. If I open Firefox, I can do this document.getElementById("login").value and it returns the correct value.

Is WebElement.GetAttribute implemented differently in the FirefoxDriver or am I just missing something?


回答1:


It's hard to say in your case why is not working on Firefox, there is no different implementation between browsers. You can try alternate solution using IJavascriptExecutor instead as below :-

IJavaScriptExecutor js = driver as IJavaScriptExecutor;
string Text = (string)js.ExecuteScript("return arguments[0].value", WebElement);



回答2:


The Selenium protocol to get an attribute/property has evolved with Selenium 3.

With Selenium 2, the method WebElement.GetAttribute(...) returns the HTMLElement property when present and the attribute otherwise.

With Selenium 3, there's a distinctive command to get the property and one for the attribute : https://www.w3.org/TR/webdriver/#get-element-property

In your case it seems that you are using the geckodriver (Selenium 3) with a client limited to the Selenium 2 specs. It would explain why the property is not returned.

To make it work, you can either upgrade your C# client to V3.0.0-beta2: https://github.com/SeleniumHQ/selenium/blob/master/dotnet/CHANGELOG https://github.com/SeleniumHQ/selenium/commit/a573338f7f575ccb0069575700f2c059dc94c3b8

Or you can implement your own GetProperty in a method extension:

static string GetProperty(this IWebElement element, string property) {
    var driver = (RemoteWebDriver)((RemoteWebElement)element).WrappedDriver;
    var result = (IList)driver.ExecuteScript(@"
        var element = arguments[0], property = arguments[1];
        if (property in element) return [true, '' + element[property]];
        return [false, 'Missing property: ' + property];
      ", element, property);

    bool succeed = (bool)result[0];
    if (!succeed) throw new WebDriverException((string)result[1]);

    return (string)result[1];
}

Usage:

string value = driver.FindElement(...).GetProperty("value");


来源:https://stackoverflow.com/questions/39175190/getattribute-of-webelement-in-selenium-firefox-driver-returns-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!