《SeleniumBasic 3.141.0.0

如具有Selenium编程经验,一定很熟悉浏览器和驱动文件的配置,本节可以跳过。下面只给零基础的学员讲解。

Selenium技术实现过程会用到4个层次的东西:编程语言+对象库+驱动+浏览器,示意图如下:

在第一节课中,我们已经搞定了编程语言+对象库,对于V3来说,我们用的是VBA+SeleniumBasic.tlb

  • 浏览器的安装和确认

下面仅以Chrome浏览器为例,如果你的电脑还没有安装该浏览器,请自行下载该浏览器的安装程序进行安装,虽然在我的微云也分享了浏览器的安装包。

但是大家从百度也很容易下载到这些。

安装完成后,文件夹中找到如下路径:"C:Program Files (x86)GoogleChromeApplicationchrome.exe"

会看到Chrome.exe这个图标,这就是浏览器的启动位置。

  • 驱动文件的下载

驱动文件必须与浏览器的版本匹配。打开Chrome浏览器,在帮助菜单中确认一下版本号:V 85.0。

然后打开网页: http://chromedriver.storage.googleapis.com/index.html,找到以85开头的文件夹,点击开。

 把win32.zip那个压缩包下载下来,解压到习惯的路径下。

 在我的电脑,解压到了 E:SeleniumDrivers路径下。

可以看到一个chromedriver.exe文件。

以上工作完成后,再次运行第一节课中的Sub Baidu,会看到自动打开了Chrome浏览器,并且打开了百度搜索,输入了好看视频。

 然后在立即窗口看到该网页的标题、URL、HTML源代码等信息。

Private WD As SeleniumBasic.IWebDriver
Sub Baidu()
    On Error GoTo Err1
    Dim Service As SeleniumBasic.ChromeDriverService
    Dim Options As SeleniumBasic.ChromeOptions
    Set WD = New SeleniumBasic.IWebDriver
    Set Service = New SeleniumBasic.ChromeDriverService
    With Service
        .CreateDefaultService driverPath:="E:SeleniumDrivers"
        .HideCommandPromptWindow = True
    End With
    Set Options = New SeleniumBasic.ChromeOptions
    With Options
        .BinaryLocation = "C:Program Files (x86)GoogleChromeApplicationchrome.exe"
        '.AddExcludedArgument "enable-automation"
        '.AddArgument "--start-maximized"
        '.DebuggerAddress = "127.0.0.1:9999" '不要与其他几个混用
    End With
    WD.New_ChromeDriver Service:=Service, Options:=Options
    WD.URL = "https://www.baidu.com"
    Dim form As SeleniumBasic.IWebElement
    Dim keyword As SeleniumBasic.IWebElement
    Dim button As SeleniumBasic.IWebElement
    Set form = WD.FindElementById("form")
    Set keyword = form.FindElementById("kw")
    keyword.Clear
    keyword.SendKeys "好看视频"
    Set button = form.FindElementById("su")
    button.Click
    Debug.Print WD.Title, WD.URL
    Debug.Print WD.PageSource
    MsgBox "下面退出浏览器。"
    WD.Quit
    Exit Sub
Err1:
    MsgBox Err.Description, vbCritical
End Sub

 以上只是讲了SeleniumBasic的入门知识,接下来陆续学习定位元素等内容。

原文地址:https://www.cnblogs.com/ryueifu-VBA/p/13661378.html