前言
在selenium web-UI自動化測試之前我們需要配置環境變量,安裝包插件等,其中最重要的就是chromedriver瀏覽器。
配置好了chromedriver我們才能成功的打開瀏覽器,但是安裝過程卻是比較麻煩的,比如我們需要先下載chromedriver插件,然后配置環境變量,什么都配置好了,才能使用selenium打開瀏覽器。
有沒有更好更簡便的方法呢,還真有這樣一個簡便的方法。
Github上面有人就開源了一個chromedriver-py庫。
安裝
首先呢,刪除本機的chromedriver
rm /usr/local/bin/chromedriver
然后呢,我們需要安裝這個庫:
- MacOS和Linux平台
python3 -m pip install chromedriver-py
- win平台
pip install chromedriver-py
安裝過程:
$ python3 -m pip install chromedriver-py
Looking in indexes: http://mirrors.aliyun.com/pypi/simple/
Collecting chromedriver-py
Downloading http://mirrors.aliyun.com/pypi/packages/6c/7e/96661812736a0d896f445752c3ebf31baf0d86d0dddeae50a0048d1fe42b/chromedriver_py-87.0.4280.88-py3-none-any.whl (19.6 MB)
|████████████████████████████████| 19.6 MB 5.9 MB/s
Installing collected packages: chromedriver-py
Successfully installed chromedriver-py-87.0.4280.88
WARNING: You are using pip version 20.1.1; however, version 20.3.1 is available.
You should consider upgrading via the '/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -m pip install --upgrade pip' command.
編寫腳本測試一下
首先我們需要導入兩個模塊
import time
from selenium import webdriver
from chromedriver_py import binary_path
然后編寫啟動瀏覽器
driver = webdriver.Chrome(executable_path=binary_path)
這里在driver初始化的時候一定要指定executable_path參數為chromedriver_py模塊的binary_path變量。
driver.get('https://www.baidu.com')
time.sleep(3)
driver.quit()
然后執行,成功啟動瀏覽器,打開百度,停留3秒關閉。
探究
我們一起找找chromedriver在哪里下載着,首先我們是用pip
命令安裝的,所以我們進入site-package
目錄下看看。
在里面找到了chromedriver_py的文件夾。我們打開:
會發現,它會給你自動下載了三個平台的chromedriver的驅動包。然后python這樣運行的時候就會被執行了。
這個真的很方便也很實用。最后推薦大家使用這種方式。