簡體   English   中英

如何使用Selenium WebDriver,NUnit和C#獲取元素屬性的子屬性值

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

我正在使用Selenium WebDriver測試網站,但是我很難獲得作為另一個財產的子財產的財產的價值。 對我來說,這個2nd / child級別總是返回null。

嘗試獲取上層屬性/屬性的值時,可以使用以下代碼正常工作:

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

您可以使用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更多詳細信息,您可以在這里找到。 您可以在如何使用Selenium,C#從dom元素中獲取所有CSS樣式中找到有關CSS和Selenium的所有其他信息

看來您已經很接近了。 要檢索cssTextfontWeight ,可以使用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方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM