How to read Config Files in Python using Selenium
By Aakash Makwana, Community Contributor - September 1, 2022
In today’s fast-paced world where AI is gaining popularity, automation testing in agile has become very critical. Any mundane task that takes up time needs to be automated. Automation cuts down on a lot of manual working time. When a website is published, a lot of testing is done to ensure that it is functioning properly.
Imagine, that you are manually testing a website in terms of navigation – it takes 10 minutes to test the website for a particular browser thoroughly.
- Now, there are several browsers with different versions on different devices.
- Assuming that you are testing it on 5 different browsers, each having 5 different versions for 5 different devices.
- the total manual test time will be (5 browsers X 5 versions X 5 devices X 10 minutes) = 1250 minutes (which is approximately 21 hours).
- Also, this time will increase exponentially
Thus, we need browser automation to reduce such manual time and effort. In such automation, we can specify the tests we want to perform over different devices or browsers. The information regarding all the possible devices and browsers (you want to test) is usually stored in a config file. Let’s understand how to read a config file in python in a brief manner going ahead.
What is a Config File?
Here, config stands for configuration. So, simply put, that file contains configuration information in a key, value format. There are several config file formats (a few popular among them are):
1. JSON Configuration Files
It stands for JavaScript Object Notation. It stores information in a key-value pair.
e.g.
{ "Example": { "Language": [ "Python" ], "Modules": [ "Selenium", ], "Enabled": 1 } }
2. YAML Configuration Files
It stands for YAML Ain’t Markup Language. It also stores information in a key-value pair. The structure is slightly different from JSON.
e.g.
Language: 'Python' Modules: - 'Selenium' Enabled: 1
3. INI Configuration Files
It stands for INItialization file. It is very intuitive to parse and understand.
e.g.
[example] Language=Python Modules=Selenium enabled=1
4. XML Configuration Files
It stands for EXtensible Markup Language. It stores information in tags. Each tag name represents the property and the tag value corresponds to the tag value.
e.g.
<example> <language>Python</language> <modules priority="1">Selenium</modules> <enabled>1</enabled> </example>
All the above four configuration files convey the same information.
- The configuration name is Example.
- The Language within that configuration is Python.
- The Module within that configuration is Selenium.
The Enabled flag within that configuration is set to 1.
Understanding the role of Python & Selenium in Automation
Python is the most popular programming language in recent times. It has several libraries for catering use cases like web scraping, automation, etc. Selenium is a very popular python library commonly used for automation testing. It can be used to perform tasks like:
- Visit a webpage
- Click on several clickable elements of the page
- Scroll a page
- Type something on the Input box within a page
- Pressing keys
- Even playing browser-based games
There are several other applications of Selenium. In this article, we will focus on using Selenium for a python selenium config file test case. The test case will be stored in a config file, and we will extract the data from that config file in Python language and then execute the test case using Selenium.
Try Selenium Automation for Free
Prerequisites – Initial Requirements
Step 1: Install Python
- If you are using Windows OS, you need first to install Python. You can download Python using this link.
- If you are using a Mac system, Python comes preinstalled on macOS since version 10.8
- Python comes preinstalled on most Linux distributions
- If you are a beginner and want to not get in the nitty-gritty of installing standalone python, you can download Anaconda. It is a simple framework that does all the heavy lifting installation, you can download it from here.
Step 2: Install Selenium
Once you have installed Python, you can open the command line (for windows) or the terminal (for Mac and Linux) and simply use the pip command like below to install Selenium.
pip install selenium
Step 3: Download chromedriver
Selenium needs a web driver to simulate a browser visit. Supported browsers are:
- Chrome
- Firefox
- Internet Explorer
- Safari
- Opera
- PhantomJS (invisible)
In this article, we will explore using Chrome and Firefox browsers.
For that we need to download the relevant chromedriver from the below location:
And relevant geckodriver for Firefox from below location:
You need to store the chromedriver.exe and GeckoDriver in the folder where you are running your code.
Problem Statement
We will have a very simple test case of opening Google and searching for a search_term and pressing enter. This search_term will be stored in a config file browserstack_config_v2.json That file contains the below configuration
{ "browsers": [ { "browser": "chrome", "browser_version": "latest", "search_term": "browserstack" }, { "browser": "firefox", "browser_version": "latest", "search_term": "browserstack automate" } ] }
Let us read this config file and perform the test case.
Step 1: Import necessary libraries
Python Code:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Options import json import warnings warnings.filterwarnings("ignore")
Step 2: Load the config file
We will use the JSON library to load the json file containing configuration.
Python Code:
with open('browserstack_config_v2.json') as json_file: config_data = json.load(json_file) print(config_data)
Output:
{'browsers': [{'browser': 'chrome', 'browser_version': 'latest', 'search_term': 'browserstack'}, {'browser': 'firefox', 'browser_version': 'latest', 'search_term': 'browserstack automate'}]}
Now, the config_data variable contains the configuration stored as a dictionary.
Step 3: Load the configuration of the first browser and perform the test.
We will load the first configuration, and write our entire test case. We will also print whether the test is successful or unsuccessful. Once, the test case runs, we will also close the driver
Python Code:
curr_config = config_data['browsers'][0] curr_browser = curr_config['browser'] curr_search_term = curr_config['search_term'] if(curr_browser=='chrome'): driver = webdriver.Chrome('path to your chromedriver.exe') elif(curr_browser=='firefox'): driver = webdriver.Firefox(executable_path=''path to your geckodriver.exe') try: print('1. Opening Website') url = 'http://www.google.com' driver.get(url) print('2. Performing test') inputElement = driver.find_element(By.NAME, 'q') inputElement.send_keys(curr_search_term) inputElement.submit() print('3. Test is Successful') except Exception as e: print('Test is Unsuccessful') driver.close()
It will invoke a Selenium session i.e. it will open a Chrome browser and do the actions we coded.
Also, additionally, it will print whether the test is successful or unsuccessful. For our example, the test ran successfully, so we see the below output:
- Opening Website
- Performing test
- Test is Successful
Step 4: Putting it all together (we will save the entire python code as selenium_test.py)
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by import By import json import warnings warnings.filterwarnings("ignore") with open('browserstack_config_v2.json') as json_file: config_data = json.load(json_file) for curr_config in config_data['browsers']: curr_browser = curr_config['browser'] curr_search_term = curr_config['search_term'] if(curr_browser=='chrome'): driver = webdriver.Chrome('path to your chromedriver.exe') elif(curr_browser=='firefox'): driver = webdriver.Firefox(executable_path=’path to your geckodriver.exe') try: print('1. Opening Website') url = 'http://www.google.com' driver.get(url) print('2. Performing test') inputElement = driver.find_element(By.NAME, 'q') inputElement.send_keys(curr_search_term) inputElement.submit() print('3. Test is Successful') except Exception as e: print('Test is Unsuccessful') driver.close()
Step 5: Execute the command to run the test
You can open the command line (for windows) or the terminal (for Mac and Linux) and execute the below command
python selenium_test.py
Output:
- Opening Website
- Performing test of searching: browserstack
- Test is Successful
- Opening Website
- Performing test of searching: browserstack automate
- Test is Successful
Key Takeaways
When a website is published, thorough testing needs to be done to ensure its proper functioning. Using browser automation, we can specify those tests we would want to perform over different devices or browsers. The information regarding all the possible devices and browsers (you want to test) is usually stored in a config file. This article covered automating the cross-browser testing process through the python selenium config file. It covered different aspects of how to read a config file in python including cross-browser testing and performing searches on the Google website.
Harnessing the full potential of Selenium and Python goes a long way in enabling developers and QA to inspect, automate, and validate website functionality.