如何使用Selenium,C#从dom元素中获取所有CSS样式
问题描述:
我的任务是从网页创建最小化的CSS文件.因此,我需要来自所有dom元素的所有css属性的值. 但是我不知道:如何从特定的dom元素中获取所有经过计算的CSS样式?
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?
我有以下代码:
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 styles = domElement.GetComputedCssStyles();
答
,您可以使用IWebElement
的getCSSValue
方法.例如,要获取元素的背景色,您可以尝试以下代码.
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");
请您可以使用Selenium C#尝试以下javascript代码;
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]);
}