selenium3 webdriver啟動火狐、chrome、edge、Safari瀏覽器的方法
在selenium2中啟動常見的火狐、chrome其實都比較簡單,網上也一堆教程。現在selenium最新版已經是 3.x的版本了,與selenium2其實沒有太大的區別,無非就是精簡了一些不用的東西,然後對於瀏覽器的支援更好了,比如,對於高版本的firefox、chrome、edge等都可以完美支援,這樣我們就不用受限於版本的問題了。
但很多童鞋在用selenium3啟動瀏覽器的時候都會遇到各種問題,雖然網上也有不少解決方法,但沒有一個彙總的,而且解決方法也太過於複雜,所以這次我就總結一下在python中使用selenium3啟動常用瀏覽器的方法。
前提
安裝好python3,並配置好環境變數
selenium3 webdriver啟動火狐瀏覽器
1、選擇對應的Mozilla GeckoDriver下載,地址:https://github.com/mozilla/geckodriver/releases
2、把壓縮包裡的exe檔案放到python的根目錄裡
3、安裝最新版的火狐,必須高於48版本
4、執行程式碼啟動
from selenium import webdriver
#方式1:直接啟動瀏覽器
driver = webdriver.Firefox()
''' 方式2: 通過指定profile來啟動瀏覽器 好處就是啟動瀏覽器是帶著咱們配置好的設定的 檢視profile的檔案路徑方法為: 火狐選單>幫助>故障排除資訊>顯示資料夾 ''' #定義profile檔案路徑 profile_ff = "你實際的profile檔案的全路徑,注意轉義字元" #指定使用該profile fp = webdriver.FirefoxProfile(profile_ff) #啟動瀏覽器時載入指定的profile driver = webdriver.Firefox(fp)
小提示:如果不想讓火狐自動升級,可以做如下改動:進入火狐安裝目錄下的defaults下的pref,修改channel-prefs.js,內容最終改為:pref("app.update.channel", "default");
selenium3 webdriver啟動chrome瀏覽器
1、選擇對應的Google Chrome Driver下載,地址:https://sites.google.com/a/chromium.org/chromedriver/downloads
2、把壓縮包裡的exe檔案放到python的根目錄裡
3、安裝最新版的chrome
4、執行程式碼啟動
from selenium import webdriver #方式1:直接啟動瀏覽器 driver = webdriver.Chrome()
#方式2:chrome的profile,瀏覽器裡輸入chrome://version/,檢視自己的“個人資料路徑”
profile_chrome = '--user-data-dir=自己chrome profile的全路徑'
option=webdriver.ChromeOptions()
option.add_argument(profile_chrome)
driver=webdriver.Chrome(chrome_options=option)
selenium3 webdriver啟動edge瀏覽器
1、先檢視自己電腦上edge的版本號(html的)
2、然後下載對應版本的Microsoft Edge Driver,地址:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
3、把exe放到python根目錄下
4、寫程式碼執行
from selenium import webdriver
driver = webdriver.Edge()
selenium3 webdriver啟動Safari瀏覽器
簡單到懷疑人生,直接寫程式碼執行
from selenium import webdriver
driver = webdriver.Safari()