Selenium with Python using Geckodriver for Firefox in Kali Linux

Selenium seems to be great for browser automation and has support for multiple programming languages, including my favorite – Python. I decided to test it on Kali Linux and faced certain issues. So I resolved them one at a time and I am logging the procedure here.

Installing Selenium

First, we need to install the Selenium module in Python using pip install. This is simply:

apt-get install python-pip 
pip install selenium

This should install the latest version of Selenium module. Test it by going to the Python command line and importing the module:

from selenium import webdriver

 This works. What does not work is following test code:

browser = webdriver.Firefox()
browser.get('https://lifeofpentester.blogspot.com/')

It fails saying: webdriverexception: geckodriver executable needs to be in path.

To resolve this, we need to install geckodriver.

Installing Geckodriver

Grab geckodriver from its Github here: https://github.com/mozilla/geckodriver/releases

I grabbed Linux64 bit version since I am running Kali Linux 64 bit. Unpack the archive and make the geckodriver executable and copy it so that Python can find it:

root@amirootyet:~# chmod +x Downloads/geckodriver  
root@amirootyet:~# cp Downloads/geckodriver /usr/local/bin

 Now we are faced with a new error:

selenium.common.exceptions.WebDriverException: Message: connection refused  

The problem here is that the latest version of Selenium that we installed cannot interface with the older version of Firefox that comes bundled with Kali Linux. I do have the latest version of Firefox downloaded and unzipped. 

Loading the correct Firefox version

So now we point Selenium to use this latest binary of Firefox instead:

from selenium.webdriver.firefox.firefox\_binary import FirefoxBinary
binary = FirefoxBinary('/root/Downloads/firefox/firefox')
driver = webdriver.Firefox(firefox\_binary=binary)

Of course, you need to ensure that paths are correct pertaining to your system and where you downloaded and unzipped Firefox. At this point, we can get this Python script to open a webpage for us:

from selenium import webdriver  
from selenium.webdriver.firefox.firefox\_binary import FirefoxBinary  
binary = FirefoxBinary('/root/Downloads/firefox/firefox')  
driver = webdriver.Firefox(firefox\_binary=binary)  
driver.get('https://www.lifeofpentester.blogspot.com')
# insert time.sleep() here  
driver.close()

So now that we have some browser automation going, I will post more results and scripts such as logging into web forms using automated Selenium scripts when I find time. Let me know in comments if this solution worked for you.

Pranshu Bajpai
Pranshu Bajpai
Principal Security Architect

Pranshu Bajpai, PhD, is a principle security architect..