How to get all css-styles from a dom-element using Selenium, C#

℡╲_俬逩灬. 提交于 2020-01-06 08:03:34

问题


My task is to create a minimized css-file from a web-page. And so I need values from all css-properties from all dom-elements. But I don't know: How to get all computed css-styles from a specific dom-element?

I have the following code:

var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");

var browser = new ChromeDriver(chromeOptions);

var url = "https://example.com";
browser.Navigate().GoToUrl(url);

var domElement = browser.FindElement(By.TagName("html"));

And I want:

var styles = domElement.GetComputedCssStyles();

回答1:


you can use getCSSValue method of IWebElement. For example to get the background color of a element you can try the following code.

var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");

var browser = new ChromeDriver(chromeOptions);

var url = "https://example.com";
browser.Navigate().GoToUrl(url);

var domElement = browser.FindElement(By.TagName("html"));
var color = domElement.GetCssValue("background-color");

May you can try the following javascript code using selenium C#;

string properties = ((IJavaScriptExecutor)driver).ExecuteScript("return window.getComputedStyle(arguments[0],null).cssText", domElement);
strArr = properties.split(";")

for (count = 0; count <= strArr.Length - 1; count++)
{
    console.log(strArr[count]);
}



回答2:


To get all the computed css-styles from a specific dom-element you can use the following line of code:

  • C#:

    ((IJavaScriptExecutor)driver).ExecuteScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", myElem);
    
  • Sample (Java) Code Block:

    WebDriver driver = new FirefoxDriver();
    driver.get("https://www.google.com/");
    WebElement myElem = driver.findElement(By.name("q"));
    System.out.println(((JavascriptExecutor)driver).executeScript("var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;", myElem).toString());
    
  • Console Output:

    {aria-autocomplete=list, aria-haspopup=false, aria-label=Search, autocomplete=off, class=gsfi lst-d-f, dir=ltr, id=lst-ib, maxlength=2048, name=q, role=combobox, spellcheck=false, style=border: medium none; padding: 0px; margin: 0px; height: auto; width: 100%; background: transparent url("data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw%3D%3D") repeat scroll 0% 0%; position: absolute; z-index: 6; left: 0px; outline: medium none currentcolor;, title=Search, type=text, value=}
    


来源:https://stackoverflow.com/questions/50601267/how-to-get-all-css-styles-from-a-dom-element-using-selenium-c-sharp

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