最近研究一个如何在网页定位验证码并截图的问题时, 用SS写了一段C#小脚本可以轻松获取页面任意元素的布局信息 (top, left, width, height). 10行功能代码, 觉得有点用, 现分享给大家:
public dynamic GetRect(JQueryContext node) { node.Attr("pos_top", "0"); node.Attr("pos_left", "0"); Default.RunScript(string.Format("var pos = $('{0}').position();$('{0}').attr('pos_top', pos.top);$('{0}').attr('pos_left', pos.left);", node.JQueryExpression)); return new { top = node.Attr("pos_top"), left = node.Attr("pos_left"), width = node.Css("width"), height = node.Css("height") }; }
- 基本思路是利用JQuery获取元素的position, 并临时保存在pos_top和pos_left属性中, 然后用JQuery将这两个属性的值读取出来即可.
在SS中调用并测试:
public void Run() { Logger.ClearAll(); Default.Navigate("http://www.gdtsearch.com/products.spiderstudio.codeviewer.htm"); Default.Ready(); var node = Default.SelectSingleNode("HTML:eq(0)>BODY:eq(0)>DIV:eq(0)>DIV:eq(1)>DIV:eq(0)>H2:eq(1)"); var rect = GetRect(node); node.Css("background-color", "yellow"); //将元素设为高亮背景 Logger.Log("top = " + rect.top + "px"); Logger.Log("left = " + rect.left + "px"); Logger.Log("width = " + rect.width); Logger.Log("height = " + rect.height); }
运行效果: