《SeleniumBasic 3.141.0.0 - 在VBA中操作浏览器》高级技术之十三:Firefox浏览器的自定义配置

Firefox有一个Profile的概念,用于设置用户自定义的一些内容。例如设置火狐浏览器启动后的默认主页。

SeleniumBasic中提供了两种方式,一种是创建FirefoxProfile对象,然后把它赋给FirefoxOptions,接着启动浏览器。

Private WD As SeleniumBasic.IWebDriver
Sub Taobao()
    On Error GoTo Err1
    Dim Service As SeleniumBasic.FirefoxDriverService
    Dim Options As SeleniumBasic.FirefoxOptions
    Dim Profile As SeleniumBasic.FirefoxProfile
    Set WD = New SeleniumBasic.IWebDriver
    Set Service = New SeleniumBasic.FirefoxDriverService
    With Service
        .CreateDefaultService driverPath:="E:\Selenium\Drivers"
        .HideCommandPromptWindow = True
    End With
    Set Profile = New SeleniumBasic.FirefoxProfile
    With Profile
        .SetPreference "browser.startup.homepage", "https://www.taobao.com/"
        .SetPreference "browser.startup.page", "1"
    End With
    Set Options = New SeleniumBasic.FirefoxOptions
    With Options
        .BrowserExecutableLocation = "C:\Program Files\Mozilla Firefox\firefox.exe"
        Set .Profile = Profile
    End With
    WD.New_FirefoxDriver Service:=Service, Options:=Options
End Sub

运行上述代码,火狐浏览器自动打开了淘宝主页。

 

第二种方式是不创建Profile,直接在FirefoxOptions中使用SetPreference方法。

Private WD As SeleniumBasic.IWebDriver
Sub JD()
    On Error GoTo Err1
    Dim Service As SeleniumBasic.FirefoxDriverService
    Dim Options As SeleniumBasic.FirefoxOptions
    Set WD = New SeleniumBasic.IWebDriver
    Set Service = New SeleniumBasic.FirefoxDriverService
    With Service
        .CreateDefaultService driverPath:="E:\Selenium\Drivers"
        .HideCommandPromptWindow = True
    End With
    Set Options = New SeleniumBasic.FirefoxOptions
    With Options
        .BrowserExecutableLocation = "C:\Program Files\Mozilla Firefox\firefox.exe"
        .SetPreference "browser.startup.homepage", "https://www.jd.com/"
        .SetPreference "browser.startup.page", "1"
    End With
    WD.New_FirefoxDriver Service:=Service, Options:=Options
End Sub

上述程序执行后首页是京东网。

不过第一种方式选项更加丰富,推荐使用。

posted @ 2020-10-03 12:36  ryueifu  阅读(1643)  评论(1编辑  收藏  举报