Web automation with Selenium and Python17 May 2017
I recently discovered Selenium, a very useful tool to automate browsers navigation. Selenium allows to write scripts to automatically perform actions on a web browser: visit a page, click on a link, fill in a form… and retrieve the results of these actions. In this post, I am going to show you how to use Selenium from Python to automatically send messages to a list of Flickr contact through a contact form from your Flickr account.
First you can use pip to install the selenium package.
Selenium requires a driver to interface with the chosen browser. Since we are going to use Firefox in this example, we will need to download the last release of geckodriver and add the directory containing the executable to the system path. Selenium will indeed try to locate the driver from your system path. On Unix system you can use the command export PATH=$PATH: and on windows you will need to go to System->Advanced->Environment Variables->Path->Edit. Don’t forget to restart your system after adding the path to the geckodriver executable to your system path!
You can now import the webdriver and the Firefox component from the selenium library.
Then, we import the list of Flickr users’ contact ID (one column csv file with a header).
The next step will be to create an instance of Firefox WebDriver with the command webdriver.Firefox(). It is also possible to associate this instance to an already existing Firefox profile. Since I didn’t manage to automatically log in to my fake Yahoo account with selenium I decided to create a dummy Firefox profile that contains a login cookie to Flickr. In practrice you just need to login to your Yahoo account from this profile before running the script. Firefox profiles are usually located on the AppData folder on windows AppData/Roaming/Mozilla/Firefox/Profiles/xxxx.default and in an hidden folder located on your home on Ubuntu ./mozilla/firefox/xxxx.default.
We can finally loop over the Flickr IDs, get to the url contact form of the Flickr user, and automatically fill the subject of the message and the content of the message. At this stage you need to identify what is the source code behind the object you want to interact with. You can install the Firefox plugins firebug and firepath to easily identify the paths associated with fields and click buttons on a web page.
The code above is available on my GitHub account along with a R script to download data with the Flickr API.