《SeleniumBasic 3.141.0.0 - 在VBA中操作浏览器》高级技术之十八:IE浏览器与驱动文件的部署

IE浏览器是Windows系统自带的浏览器,在VBA中一般通过InternetExplorer这个COM对象来操作浏览器,使用HTMLDocument解析网页内容。

  

SeleniumBasic技术也支持IE浏览器。本帖讲解一下通过该技术来驱动IE浏览器的知识。

  • IE浏览器驱动文件的下载

在任何一种浏览器中打开如下页面:

https://selenium-release.storage.googleapis.com/index.html

 

 

SeleniumBasic的WebDriver.dll的版本是3.141.0.0。所以要打开与WebDriver.dll版本一致的那个文件夹。也就是点击“3.141”打开。

 

 

 如果是Windows 32位系统,就下载前3个中的任意一个.zip文件。如果是64位系统,下载包含x64的即可。

把压缩包解压到E:\Selenium\Drivers路径下,可以看到多了一个IEDriverServer.exe的驱动文件,产品版本是3.141.59.0。

  • 启动浏览器

VBA中输入如下代码

Private WD As SeleniumBasic.IWebDriver
Sub Baidu()
    On Error GoTo Err1
    Dim Service As SeleniumBasic.InternetExplorerDriverService
    Dim Options As SeleniumBasic.InternetExplorerOptions
    Set WD = New SeleniumBasic.IWebDriver
    Set Service = New SeleniumBasic.InternetExplorerDriverService
    With Service
        .CreateDefaultService driverPath:="E:\Selenium\Drivers"
        .HideCommandPromptWindow = True
    End With
    Set Options = New SeleniumBasic.InternetExplorerOptions
    With Options
        .IntroduceInstabilityByIgnoringProtectedModeSettings = True
    End With
    WD.New_InternetExplorerDriver 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

运行,可以看到IE浏览器打开了百度。

  • 异常对应

 每个人电脑上的IE的设置不一定都相同,因此有些电脑运行上面的实例程序可能无法正常启动浏览器。这种情况需要事先设置浏览器。

 第1步:在浏览器右上角有个“设置”按钮,点击展开菜单,选择“Internet选项”。

 

  

 在“安全”选项卡中,依次选择“Internet”、本地Intranet、受信任的站点、受限制的站点

把“启用保护模式”前面的复选框全部去掉勾选(或者全部勾选上)。

 

 

  第2步:修改缩放比例为100%

 

 退出IE浏览器,重新运行上面的示例程序,应该可以了。

posted @ 2021-04-01 14:54  ryueifu  阅读(1189)  评论(0编辑  收藏  举报