《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系列的函数都可以赋给它。在运行过程中,可以打开本地窗口看到该数组中每个元素。

下面再讲一下如何判断元素的有无。

在网页自动化过程中,判断某个特征的元素是否存在,是相当重要的。SeleniumBasic的FindElement系列方法,当定位到一个元素时返回该元素,定位不到时返回Nothing。

    Dim button As SeleniumBasic.IWebElement
    Set button = form.FindElementById("submit")
    If button Is Nothing Then
        Debug.Print "没有找到元素。"
    Else
        button.Click
    End If

另外,FindElements系列方法,当定位到一个以上的元素时,返回元素数组。如果一个也定位不到则该数组的UBound是-1。

    Dim buttons() As IWebElement    
    buttons = form.FindElementsById("su2")
    Debug.Print IsEmpty(buttons)
    If UBound(buttons) = -1 Then
        Debug.Print "没有找到任何元素。"
    Else
        Debug.Print "找到的元素个数为", UBound(buttons) + 1
    End If

注意代码中,使用IsEmpty判断哪一行,本来没什么作用,但是不写是不行的,这可能是微软的一个问题。

posted @ 2020-09-19 09:46  ryueifu  阅读(6055)  评论(1编辑  收藏  举报