How to read Config Files in Python using Selenium

On This Page What are Configuration Files in Python?April 24, 2026 · 10 min read · Tool Comparison

How to read Config Files in Python using Selenium

Managing configuration settings efficiently is significant when automating web covering with in Python. Config register let you store environment-specific parameters separately and load them dynamically within your Selenium scripts.

Overview

What are Configuration Files in Python?

Configuration file in Python are external files that store an application & # 8217; s settings, parameters, and preferences. These files let developers separate configuration particular from the main code.

Types of Configuration Files in Python

  • JSON Configuration Files
  • YAML Configuration Files
  • INI Configuration Files
  • XML Configuration Files

In this guide, learn more about several methods of say config files in Python and integrating them effectively with Selenium automation.

What are Configuration Files in Python?

Configuration files in Python are external file that store setting, parameters, and penchant for an application. These files let developer separate configuration details from the chief codification which makes the application more modular and simpler to contend.

These file contain information like database credential, API key, file paths, and user-defined scene.

The common formats or types for configuration files in Python are INI files, JSON file, YAML files, and ENV files.

Read More:

Why Are Configuration Files Needed in Python?

Configuration plays a crucial role in software ontogenesis and automation and offers a lot of benefits:

  • Easier Maintenance: Updating settings without modifying source code reduces the risk of errors.
  • Security:Storing credentials separately prevents hardcoding sensitive info in scripts.
  • Portability:Allows the same handwriting to work across different environments (development, testing, production) without modifications.
  • Automation:Important for frameworks like Selenium, where different browser settings and certification are required for automation.

Types of Configuration Files in Python

Python supports multiple types of configuration files, each with its unique structure and use case. These formats assist shop and manage application background efficiently. This makes it easygoing to update form without alter code.

This section continue some of the common character of configuration files, including INI, JSON, YAML, and ENV file.

1. JSON Configuration Files

It stand forJavaScript Object Notation. It shop info in a key-value pair.

Example:

{'' Example '': {'' Language '': ['' Python ''], '' Modules '': ['' Selenium '',], '' Enabled '': 1}}

2. YAML Configuration Files

It stands forYAML Ain & # 8217; tMarkup Language. It also stores information in a key-value pair. The structure is slightly different from JSON.

Example:

Language: 'Python' Modules: - 'Selenium' Enabled: 1

3. INI Configuration Files

It stand forINItialization file. It is really nonrational to parse and understand.

Example:

[instance] Language=Python Modules=Selenium enabled=1

4. XML Configuration Files

It stands for EXtensible Markup Language. It memory info in tags. Each tag name represents the belongings and the tag value match to the tag value.

Example:

& lt; example & gt; & lt; language & gt; Python & lt; /language & gt; & lt; modules priority= '' 1 '' & gt; Selenium & lt; /modules & gt; & lt; enabled & gt; 1 & lt; /enabled & gt; & lt; /example & gt;

All the above four configuration file convey the same information.

  • The configuration gens isExample. 
  • The Language within that configuration isPython.
  • The Module within that constellation isSelenium.

The Enabled flag within that configuration is set to1.

Read More:

What is ConfigParser?

ConfigParser is a built-in Python module for managing configuration files in the INI format. It facilitates reading, write, and modifying configuration settings store in integrated key-value pairs under different sections.

It is utilitarian for managing scope like database connections, API credentials, and user preferences in a integrated and readable format.

ConfigParser Benefits

  • Human-Readable Format: INI files are leisurely to say and realize, still for non-programmers.
  • Structured Data Management: Organizes configurations into sections and key-value pairs for better clarity.
  • Flexibility: Allows modification of configuration settings without vary the source code.
  • Built-in Support in Python: No need for external dependencies, as ConfigParser is include in Python ’ s standard library.

Read More:

Managing Python Configuration Files with ConfigParser

There are multiple steps involved in managing configuration files expend ConfigParser, from creating and read files to update and write new configurations. Check out this step-by-step tutorial:

Step 1: Install and Import ConfigParser

Since ConfigParser is a built-in faculty in Python, no additional installment is need. You can simply spell it:

import configparser

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Step 2: Create a Configuration File

A conformation file should be created with sections and key-value pairs:

[Settings] username = admin password = secret url =

Step 3: Read Configuration Files

config = configparser.ConfigParser () config.read ('config.ini ') username = config ['Settings '] ['username '] password = config ['Settings '] ['password '] url = config ['Settings '] ['url '] print (f'Username: {username}, URL: {url} ')

Step 4: Modify Configuration Files

To update an be conformation setting:

config.set ('Settings ', 'username ', 'new_admin ') with open ('config.ini ', ' w ') as configfile: config.write (configfile)

Step 5: Add New Sections and Keys

config.add_section ('Database ') config.set ('Database ', 'host ', 'localhost ') config.set ('Database ', 'port ', '5432 ') with open ('config.ini ', ' w ') as configfile: config.write (configfile)

Step 6: Remove Sections or Keys

To delete a subdivision or a specific key:

config.remove_section ('Database ') config.remove_option ('Settings ', 'password ') with unfastened ('config.ini ', ' w ') as configfile: config.write (configfile)

Read More:

Better Practices for Managing Configuration Files in Python

Here are some of the best practices to be followed for managing configuration files in Python:

  • Use the Right Format: Choose a formatting that best suits your covering needs like INI, JSON, YAML, ENV.
  • Use Environment Variables for Sensitive Data: Avoid storing API keys and countersign in plain text within configuration files.
  • Use a Centralized System: For large-scale applications, reckon using a centralized system like AWS Parameter Store or HashiCorp Vault.
  • Encrypt Sensitive Information: If storing credentials in a config file, use encryption or secure vaults to protect them.
  • Automate Configuration Loading: Use scripts or libraries likedotenvto automate loading conformation dynamically.

Read More:

Understanding the persona of Python & amp; Selenium in Automation

is the near popular programming speech in late clip. It has several libraries for catering use cases like, automation, etc. is a very popular python library commonly used for. It can be used to execute tasks like:

  1. Visit a webpage
  2. Click on several clickable elements of the page
  3. Scroll a page
  4. Type something on the Input box within a page
  5. Pressing keys
  6. Even playing browser-based games

There are various former applications of. In this article, we will focus on using Selenium for apython selenium config file. The test example will be stored in a config file, and we will extract the data from that config file in Python words and then execute the test case using Selenium.

Talk to an Expert

Prerequisites – Initial Requirements

Step 1: Install Python

  • If you are using Windows OS, you ask first to install Python. You can download Python usingthis link.
  • If you are expend a Mac system, Python comes preinstalled on macOS since version 10.8
  • Python comes preinstalled on most Linux dispersion
  • If you are a beginner and require to not get in the nitty-gritty of installing standalone python, you can download Anaconda. It is a uncomplicated framework that perform all the heavy lifting installation, you can download it fromhere.

Step 2: Install Selenium

Once you have installed Python, you can open the bidding line (for windows) or the terminal (for Mac and Linux) and just 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 browser are:

  • Chrome
  • Firefox
  • Internet Explorer
  • Safari
  • Opera
  • PhantomJS (invisible)

In this article, we will explore using Chrome and Firefox browsers.

For that we necessitate to download the relevant chromedriver from the below location:

And relevant geckodriver for Firefox from below position:

You ask to store the chromedriver.exe and GeckoDriver in the folder where you are running your code.

Read More:

Problem Statement

Here you have a very simple test case of opening Google and research for asearch_termand exhort enter. Thissearch_termwill be stored in a config filebrowserstack_config_v2.jsonThat file contains the below configuration

{'' browsers '': [{'' browser '': `` chrome '', '' browser_version '': `` latest '', '' search_term '': `` browserstack ''}, {'' browser '': `` firefox '', '' browser_version '': `` up-to-the-minute '', '' search_term '': `` browserstack automate ''}]}

Here, you will be guided on how to read this config file and perform the trial case.

Step 1: Import necessary library

Python Code:

from selenium import webdriver from selenium.webdriver.common.by importation By from selenium.webdriver.firefox.options import Options import json meaning warnings warnings.filterwarnings (`` ignore '')

Step 2: Load the config file

We will use the JSON library to load the json file hold configuration.

Python Code:

with open ('browserstack_config_v2.json ') as json_file: config_data = json.load (json_file) mark (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 1st browser and perform the exam.

We will load the first configuration, and write our entire test case. We will besides publish whether the examination is successful or stillborn. 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: mark (' 1. Opening Website ') url = 'http: //www.google.com' driver.get (url) mark (' 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 activity we cypher.

Also, additionally, it will print whether the test is successful or unsuccessful. For our illustration, the test ran successfully, so we see the below output:

  1. Opening Website
  2. Performing examination
  3. Test is Successful

Step 4: Putting it all together (we will save the entire python code as selenium_test.py)

from selenium signification webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.common.by meaning By import json import monition 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:

  1. Opening Website
  2. Performing test of searching: browserstack
  3. Test is Successful

Conclusion

Reading configuration file in Python using Selenium improves by get test code more maintainable, scalable, and easy to interpret. Using libraries like configparser for .ini file, json for JSON, and yaml for YAML allows testers to manage browser settings, credentials, and early parameter efficiently. This assist to define tests to run across multiple devices and browser.

Also, it simplifies through consistent and reliable tests across multiple browser. Harnessing the total potentiality of goes a long way in enabling developers and QA to inspect, automate, and validate website functionality. Using tools like BrowserStack along with Selenium can help you run cross-browser and real-device tests seamlessly across 3500+ real-device-browser-OS combinations.

Utilitarian Resources for Selenium and Python

Tags
26,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free