1. 程式人生 > 實用技巧 >《SeleniumBasic 3.141.0.0 - 在VBA中操作瀏覽器》系列文章之四:元素定位

《SeleniumBasic 3.141.0.0 - 在VBA中操作瀏覽器》系列文章之四:元素定位

SeleniumBasic的IWebDriver和IWebElement兩個物件下面,都有如下16個函式,用於定位其他元素。

  1. Function FindElementByClassName(className As String) As IWebElement
  2. Function FindElementByCssSelector(cssSelector As String) As IWebElement
  3. Function FindElementById(id As String) As IWebElement
  4. Function FindElementByLinkText(linkText As String) As IWebElement
  5. Function FindElementByName(Name As String) As IWebElement
  6. Function FindElementByPartialLinkText(partialLinkText As String) As IWebElement
  7. Function FindElementByTagName(tagName As String) As IWebElement
  8. Function FindElementByXPath(xpath As String) As IWebElement
  9. Function FindElementsByClassName(className As String) As IWebElement()
  10. Function FindElementsByCssSelector(cssSelector As String) As IWebElement()
  11. Function FindElementsById(id As String) As IWebElement()
  12. Function FindElementsByLinkText(linkText As String) As IWebElement()
  13. Function FindElementsByName(Name As String) As IWebElement()
  14. Function FindElementsByPartialLinkText(partialLinkText As String) As IWebElement()
  15. Function FindElementsByTagName(tagName As String) As IWebElement()
  16. 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系列的函式都可以賦給它。在執行過程中,可以開啟本地視窗看到該陣列中每個元素。