Selenium C# 如何获取指定class类对应的全部样式属性
你之前调用GetAttribute("style")只能拿到内联样式属于正常情况,这个方法本身只能读取元素DOM节点上绑定的style属性值,也就是你示例里element.style对应的内容,.Content类选择器定义的样式不属于元素内联属性,所以无法通过这个方法获取。
你可以根据需求选择以下两种方案实现:
方案1:获取元素实际生效的计算样式(推荐)
这个方案拿到的是元素最终渲染时生效的所有样式,包含内联样式、类样式、继承样式叠加后的最终结果,符合页面实际展示效果,调用示例如下(C# Selenium):
// 先把driver转为JS执行器 IJavaScriptExecutor js = (IJavaScriptExecutor)driver; // 传入目标元素,调用浏览器原生getComputedStyle API获取计算样式 var computedStyle = js.ExecuteScript("return window.getComputedStyle(arguments[0]);", webelement) as Dictionary<string, object>; // 示例:单独取.Content类定义的两个属性值 string minHeight = computedStyle["minHeight"].ToString(); string paddingTop = computedStyle["paddingTop"].ToString();
方案2:提取样式表中.Content类的原始定义规则
如果你不需要叠加后的生效值,只需要拿到样式表中.Content选择器下写的原始样式内容,可以用遍历样式表的方案:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver; string contentRawStyles = js.ExecuteScript(@" // 遍历所有样式表查找对应选择器 for (let sheet of document.styleSheets) { try { // 跳过跨域样式表避免安全报错 for (let rule of sheet.cssRules || sheet.rules) { if (rule.selectorText === '.Content') { // 返回该类的原始样式字符串 return rule.style.cssText; } } } catch(e) {} } return ''; ") as string;
这个方案需要注意:如果.Content的样式存在跨域样式表中,会因为浏览器同源策略限制无法读取,代码中已经加了异常捕获跳过这类样式表。
内容的提问来源于stack exchange,提问作者Sharmila Kumari
相关产品推荐
相关产品推荐

