如何使用 selenium webdriver、NUnit 和 C# 获取元素 属性 的子值 属性

How to get child property value of a element property using selenium webdriver, NUnit and C#

我正在使用 selenium webdriver 测试网站,但我很难获得另一个 属性 的子项 属性 的值。对我来说,这个第二级/子级总是返回为空。

当尝试获取更高级别的值时 attribute/property 它可以正常使用以下代码:

return Element1.GetAttribute("baseURI");
return Element2.GetAttribute("innerText");

高于 return 我期望的 text/string。但是,如果我尝试获取子 属性 的值,如下所示:

return Element3.GetAttribute("style.cssText");
return Element4.GetAttribute("style.fontWeight")

我要空了。当我查看上面元素的 DOM/properties 时,我确实看到了它们的值。

cssText: "font-weight: bold;"
fontWeight: "bold"

如果我在开发人员工具栏中右键单击属性并选择 "Copy Property Path",我会得到以下信息:

style.cssText
style.fontWeight    

所以我认为问题在于我如何通过假设我从开发人员工具栏复制的内容是正确的来引用子 属性。我已经尝试了句点以外的其他分隔符,但我现在仍然很幸运。

我正在尝试找出 return 存储在 -

中的值的语法
object.style.fontWeight

我试过:

parent.child.GetCSSValue("css"), parent-child.GetCSSValue("css")
parent.child.GetAttribute("attrib"), parent-child.GetAttribute("attrib")
parent.child.GetProperty("prop"), parent-child.GetProperty("prop")

这些都返回为 null 或 empty.string

您可以使用JavaScript的getComputedStylegetPropertyValue来获取继承的样式属性值:

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

string fontWeight = (string) js.ExecuteScript("return window.getComputedStyle(arguments[0]).getPropertyValue('fontWeight')", element);

string cssText = (string) js.ExecuteScript("return window.getComputedStyle(arguments[0]).cssText", element);

有关 getComputedStyle 的更多详细信息,您可以找到 here. Everything else about css and selenium you can find in

看来你很接近。要检索 cssTextfontWeight 您可以使用 getComputedStyle() and then use getPropertyValue() 检索 样式 并且您可以使用以下解决方案:

IJavascriptExecutor jse = (IJavascriptExecutor)driver;
String cssText_script = "var x = getComputedStyle(arguments[0]);" +
        "window.document.defaultView.getComputedStyle(x,null).getPropertyValue('cssText');"; ";
String fontWeight_script = "var x = getComputedStyle(arguments[0]);" +
        "window.document.defaultView.getComputedStyle(x,null).getPropertyValue('fontWeight');"; ";
string myCssText = (string) jse.ExecuteScript(cssText_script, Element3);
string myFontWeight = (string) jse.ExecuteScript(fontWeight_script, Element4);

注意:您需要在 ExpectedConditions as ElementIsVisible 方法的同时引入 WebDriverWait