《SeleniumBasic 3.141.0.0

在Chrome浏览器上点击其他软件的安装包,或者超链接,通常会弹出一个文件保存对话框,必须手工选择文件夹和文件名称才能继续下去。

在SeleniumBasic中遇到这种情况会把程序堵死。

但是,Chrome浏览器的选项设置中,可以设置是否弹出文件保存对话框,以及保存文件的默认路径(如果不修改设置,默认位置是C:Users你的用户名DownLoad)。

SeleniumBasic中的ChromeOptions对象,具有AddUserProfilePreference方法,可以添加个人偏好。

Private WD As SeleniumBasic.IWebDriver
Sub Download()
    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.ChromeOptionsWith Options
        .BinaryLocation = "C:Program Files (x86)GoogleChromeApplicationchrome.exe"
        .AddUserProfilePreference "download.prompt_for_download", False
        .AddUserProfilePreference "download.default_directory", "D:Temp"
        Debug.Print .ToString
    End With
    WD.New_ChromeDriver Service:=Service, Options:=Options
    WD.URL = "https://www.cnblogs.com/ryueifu-VBA/p/9482006.html"
    Dim file As SeleniumBasic.IWebElement
    Set file = WD.FindElementByLinkText("TreeviewEditor.rar")
    If file Is Nothing = False Then
        WD.ExecuteScript "arguments[0].scrollIntoView(true);", file
        file.Click
    End If
    WD.Quit
    Exit Sub
Err1:
    MsgBox Err.Description, vbCritical
End Sub

上述程序执行后,打印个人偏好,可以看到设置参数成功。

{
  "browserName": "chrome",
  "goog:chromeOptions": {
    "binary": "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
    "prefs": {
      "download.prompt_for_download": false,
      "download.default_directory": "D:\Temp"
    }
  }
}

本例的目的是下载一个压缩包,网址是https://www.cnblogs.com/ryueifu-VBA/p/9482006.html。

启动浏览器后自动导航到这个网址,然后根据超链接的文字进行定位,接下来直接Click,可以看到并未弹出保存对话框,而是直接保存到了D:Temp。

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