Selenium throws Exception when use Firefox webdriver

在使用 selenium 時碰到沒辦法啟動 webdriver 的問題。

  • Experiment Environment
  • Ubuntu 14.04.5 LTS
  • Python 3.4.3
  • pip 1.5.4

Problem Description

一開始安裝好 selenium 要使用時:

1
2
from selenium import webdriver
browser = webdriver.Firefox()

這個時候會出現錯誤訊息:

1
2
3
4
5
6
7
8
Traceback (most recent call last):
File "functional_test.py", line 7, in setUp
self.browser = webdriver.Firefox()
File "/home/aweimeow/blog-django/venv/lib/python3.4/site-packages/selenium/webdriver/firefox/webdriver.py", line 140, in __init__
self.service.start()
File "/home/aweimeow/blog-django/venv/lib/python3.4/site-packages/selenium/webdriver/common/service.py", line 81, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: 'geckodriver' executable needs to be in PATH.

咦,原來是沒有 geckodriver 這個執行檔,所以要來這邊下載:Github - mozilla/geckodriver

找到適合自己版本的下載解壓縮放到執行目錄:

1
2
3
wget https://github.com/mozilla/geckodriver/releases/download/v0.11.1/geckodriver-v0.11.1-linux64.tar.gz
tar zxvf geckodriver-v0.11.1-linux64.tar.gz
sudo mv geckodriver /usr/bin

接下來再執行一次看看:

1
selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: 2

後來發現是 selenium 版本的問題,安裝 3.0.0 的 selenium

1
pip install selenium==3.0.0

Fixed!