如具有Selenium編程經驗,一定很熟悉瀏覽器和驅動文件的配置,本節可以跳過。下面只給零基礎的學員講解。
Selenium技術實現過程會用到4個層次的東西:編程語言+對象庫+驅動+瀏覽器,示意圖如下:
在第一節課中,我們已經搞定了編程語言+對象庫,對於V3來說,我們用的是VBA+SeleniumBasic.tlb
- 瀏覽器的安裝和確認
下面僅以Chrome瀏覽器為例,如果你的電腦還沒有安裝該瀏覽器,請自行下載該瀏覽器的安裝程序進行安裝,雖然在我的微雲也分享了瀏覽器的安裝包。
但是大家從百度也很容易下載到這些。
安裝完成后,文件夾中找到如下路徑:"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
會看到Chrome.exe這個圖標,這就是瀏覽器的啟動位置。
- 驅動文件的下載
驅動文件必須與瀏覽器的版本匹配。打開Chrome瀏覽器,在幫助菜單中確認一下版本號:V 85.0。
然后打開網頁: http://chromedriver.storage.googleapis.com/index.html,找到以85開頭的文件夾,點擊開。
把win32.zip那個壓縮包下載下來,解壓到習慣的路徑下。
在我的電腦,解壓到了 E:\Selenium\Drivers路徑下。
可以看到一個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:\Selenium\Drivers" .HideCommandPromptWindow = True End With Set Options = New SeleniumBasic.ChromeOptions With Options .BinaryLocation = "C:\Program Files (x86)\Google\Chrome\Application\chrome.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的入門知識,接下來陸續學習定位元素等內容。