最近研究一個如何在網頁定位驗證碼並截圖的問題時, 用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); }
運行效果:
查看本欄目