《SeleniumBasic 3.141.0.0 - 在VBA中操作瀏覽器》系列文章之四:元素定位
阿新 • • 發佈:2020-09-19
SeleniumBasic的IWebDriver和IWebElement兩個物件下面,都有如下16個函式,用於定位其他元素。
- Function FindElementByClassName(className As String) As IWebElement
- Function FindElementByCssSelector(cssSelector As String) As IWebElement
- Function FindElementById(id As String) As IWebElement
- Function FindElementByLinkText(linkText As String) As IWebElement
- Function FindElementByName(Name As String) As IWebElement
- Function FindElementByPartialLinkText(partialLinkText As String) As IWebElement
- Function FindElementByTagName(tagName As String) As IWebElement
- Function FindElementByXPath(xpath As String) As IWebElement
- Function FindElementsByClassName(className As String) As IWebElement()
- Function FindElementsByCssSelector(cssSelector As String) As IWebElement()
- Function FindElementsById(id As String) As IWebElement()
- Function FindElementsByLinkText(linkText As String) As IWebElement()
- Function FindElementsByName(Name As String) As IWebElement()
- Function FindElementsByPartialLinkText(partialLinkText As String) As IWebElement()
- Function FindElementsByTagName(tagName As String) As IWebElement()
- Function FindElementsByXPath(xpath As String) As IWebElement()
其中,前面8個函式返回的結果是一個網頁元素,後面8個都是FindElements開頭的函式,返回的是多個元素形成的陣列。
用於定位的主物件可以是瀏覽器,也可以是一個已有的網頁元素。
下面以定位百度首頁為例,程式碼片段如下:
WD.New_ChromeDriver Service:=Service, Options:=Options WD.URL = "https://www.baidu.com" Dim form As SeleniumBasic.IWebElement Dim inputs() As IWebElement Dim keyword As SeleniumBasic.IWebElement Dim button As SeleniumBasic.IWebElement Set form = WD.FindElementById("form") Set keyword = form.FindElementById("keyword") Debug.Print keyword Is Nothing inputs = form.FindElementsByTagName(tagName:="input") Debug.Print UBound(inputs) Dim i As Integer For i = 0 To UBound(inputs) Debug.Print inputs(i).tagName Next i Set keyword = form.FindElementById("kw") keyword.Clear keyword.SendKeys "好看視訊" Set button = form.FindElementById("su") button.Click
form是由瀏覽器物件WD作為主物件定位到的,其他的比如keyword,button、inputs這幾個則是從form開始定位的。
注意程式碼中的inputs是一個數組,只要是FindElements系列的函式都可以賦給它。在執行過程中,可以開啟本地視窗看到該陣列中每個元素。