SeleniumBasic的FindElement共有8個系列方法。其中XPath和CssSelector技巧性最強,其余6種定位方法很直觀簡單。
這節學習使用XPath定位一個元素周圍的其他元素。
百度首頁左上角有7個超鏈接,這些超鏈接的父親是id為s-top-left的div,爺爺是id為head的div。
首先簡單地說一下XPath的語法
//div[@id='s-top-left']/a[3]
//表示根節點,也就是WD對象。div表示根節點下的第一個div,方括號里@用於限定屬性條件,/表示下一級的路徑分隔符,a[3]表示第3個超鏈接。
注意:XPath的中括號里的索引起始於1,不是0。
上面可以概括為:查找id為s-top-left的div下面的第3個超鏈接。請看代碼:
Dim div As IWebElement
Dim map As IWebElement
Set div = WD.FindElementByXPath("//div[@id='s-top-left']")
Set map = div.FindElementByXPath("a[3]")
Set map = WD.FindElementByXPath("//div[@id='s-top-left']/a[3]")
Debug.Print map.text '地圖
Debug.Print map.FindElementByXPath("preceding-sibling::a[1]").text 'hao123
Debug.Print map.FindElementByXPath("preceding-sibling::a[2]").text '新聞
Debug.Print map.FindElementByXPath("following-sibling::a[1]").text '新聞
Debug.Print map.FindElementByXPath("following-sibling::a[2]").text '新聞
Debug.Print map.FindElementByXPath("../..").GetAttribute("id") 'head
上述程序中,首先定位到“地圖"賦給變量map,然后以map為中心,找到它的兩個哥哥和兩個弟弟(注意括號內數字的順序,數字越大表示離自己越遠)。
定位父級元素使用兩個小數點,例如../..表示定位當前元素的爺爺。所以最后一句代碼的結果是head。