2

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

当尝试获取上层属性/属性的值时,它可以使用以下代码正常工作:

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

上面的那些返回我期望的文本/字符串。但是,如果我尝试获取子属性的值,如下所示:

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

我越来越空了。当我查看上面元素的 DOM/属性时,我确实看到了它们的值。

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

如果我右键单击开发人员工具栏中的属性并选择“复制属性路径”,我会得到以下信息:

style.cssText
style.fontWeight    

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

我正在尝试找出返回存储在-中的值的语法

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 的形式返回

4

2 回答 2

1

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

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有关您的更多详细信息,请点击此处。关于 css 和 selenium 的所有其他内容,您可以在How to get all css-styles from a dom-element using Selenium, C#中找到

于 2019-02-24T15:41:54.633 回答
1

看来你已经很接近了。要检索cssTextandfontWeight您可以使用getComputedStyle()然后使用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);

注意:您需要将WebDriverWaitExpectedConditions作为ElementIsVisible方法一起引入。

于 2019-02-24T20:13:50.903 回答