How to Add Chrome Extension using Python Selenium
Last Updated :
09 Sep, 2024
Introduction
Selenium is a tool for browser automation that supports multiple browsers for testing. With webdriver we can use multiple languages like Python, C#, and Java to write the code for automation testing. For Adding a Chrome extension in a browser with Selenium WebDriver allows us to automate the browser and an extension to it.
Setting Up Selenium with Chrome
pip install selenium pyautogui
Here, we will use pyautogui to press buttons.
Adding Chrome Extension
In the below code, we only need to provide the URL of an extension.
Python
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import pyautogui
# Set up Chrome options
chrome_options = Options()
# Path to your ChromeDriver
chrome_driver_path = 'chromedriverPath'
# Initialize ChromeDriver with the specified options
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# Go to the Chrome Web Store URL of the desired extension
extension_url = 'https://chromewebstore.google.com/detail/todoist-for-chrome/jldhpllghnbhlbpcmnajkpdmadaolakh'
driver.get(extension_url)
driver.maximize_window();
# Wait for the page to load
time.sleep(5) # Adjust time as needed
actions = ActionChains(driver)
try:
# Find the "Add to Chrome" button
add_to_chrome_button = driver.find_element(By.XPATH, '//button[span[contains(text(),"Add to Chrome")]]')
# Click the "Add to Chrome" button
add_to_chrome_button.click()
time.sleep(8)
pyautogui.press('tab', presses=1)
time.sleep(1)
# Use PyAutoGUI to press Enter to confirm "Add to Extension"
pyautogui.press('enter')
# Wait for the "Add Extension" confirmation dialog
time.sleep(2)
except Exception as e:
print(f"An error occurred: {e}")
# Wait to observe the added extension
time.sleep(5)
# Close the browser
driver.quit()
Output:
Adding Local Extension to Chrome using Python Selenium
Steps to Add Chrome Extension
- Create new Directory - In which we will have all our extension files
- Create a Manifest File - This will be used describe the Extension like Name, version
- Create Html File - This will be used to design the interface to show to the user.
- Create Javascript file - This will be used to write logical code.
- Run the Selenium script to add.
manifest.json
JavaScript
{
"manifest_version": 3,
"name": "Word Counter",
"version": "1.0",
"description": "A simple Chrome extension to count words on a page.",
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"permissions": ["activeTab"],
"icons": {
"16": "icon.png",
"48": "icon.png",
"128": "icon.png"
}
}
popup.html
HTML
<!DOCTYPE html>
<html>
<head>
<title>Word Counter</title>
<style>
body {
width: 200px;
font-family: Arial, sans-serif;
text-align: center;
padding: 10px;
}
#count {
font-size: 20px;
margin: 10px 0;
}
button {
padding: 5px 10px;
font-size: 14px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Word Counter</h1>
<div id="count">Words: 0</div>
<button id="countButton">Count Words</button>
<script src="popup.js"></script>
</body>
</html>
popup.js
JavaScript
document.getElementById("countButton").addEventListener("click", () => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
chrome.scripting.executeScript(
{
target: { tabId: tabs[0].id },
func: countWords,
},
(results) => {
document.getElementById("count").innerText = `Words: ${results[0].result}`;
}
);
});
});
function countWords() {
const selection = window.getSelection().toString().trim();
const text = selection || document.body.innerText;
const wordCount = text.match(/\b\w+\b/g)?.length || 0;
return wordCount;
}
Add the extension to the Chrome Selenium Script
Python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.chrome.service import Service
# Set the path to the ChromeDriver executable
chrome_driver_path = "V:\\VISHESH AGRAWAL\\Software\\chromedriver.exe"
# Set the path to the directory containing your unpacked extension
extension_path = "V:\\VISHESH AGRAWAL\\Chrome Extension\\Word Counter"
# Configure ChromeOptions to load the extension
chrome_options = Options()
chrome_options.add_argument("load-extension=" + extension_path)
# Initialize WebDriver with the configured ChromeOptions
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# Maximize the browser window
driver.maximize_window()
# Add implicit wait
driver.implicitly_wait(10)
# Navigate to a page where you want to test the word counter
driver.get("https://www.example.com")
time.sleep(15)
# Close the browser (optional, can be removed if you don't want to close immediately)
driver.quit()
So this will easily load the extension and then we can use it according to our need.
Output:
Common Debugging Issue
While working with Selenium in chrome we generally have some common issue like Different version of Chrome and Chrome Driver. When we encounter such issue than it will throw error like "SessionNotCreatedException". Also sometime we come across the issues like not getting the element or not able to execute the operation on that element like we cannot send the keys to the button. But some of the common issue can be taken care by following the best practices which we should follow so that we don't encounter such problems while working with selenium.
Best Practices to Follow
Some best practices to follow while working with Selenium.
- Keep Tools Updated: Always have the latest version of Chrome Driver, Chrome browser, and Selenium.
- Have Virtual Environments: We generally use virtual environment for avoiding dependencies conflicts.
- Handle Exceptions: Use try-except blocks to handle exceptions for Code like finding the element or clicking the elements.
Conclusion
Using selenium with chrome we can do so many things. In selenium we have a webdriver which has been used for the automated testing of the website. Here we have used Selenium for adding chrome extension into the chrome. For this we have used python as a language and used pyautogui for clicking on the alerts which are been present in the process.
Similar Reads
How to Locate Elements using Selenium Python? Selenium: is an open-source tool that automates web browsers. It provides a single interface that lets you write test scripts in programming languages like Ruby, Java, NodeJS, PHP, Perl, Python, and C#, among others. I personally prefer Python as itâs very easy to write code in python. A browser-dri
3 min read
How to Test Chrome Extensions in Java Selenium? Testing Chrome extensions is critical as it helps confirm their capabilities and efficiency. This article will explain how to test Chrome extensions using Java Selenium, a well-known web testing tool.Table of ContentSetting Up the EnvironmentBasics of Selenium WebDriverWhat Are Chrome Extensions?Pre
6 min read
How to save and load cookies in Selenium using Python In web automation and testing, maintaining session information across different runs of scripts is often necessary. Cookies are a great way to save session data to avoid logging in repeatedly. Selenium, a popular tool for web testing, provides straightforward ways to save and load cookies using Pyth
4 min read
How to check if an element exists with Python Selenium? Selenium is one of the most powerful and widely used tools for web automating web applications. Whether you're a software developer or a QA tester, Selenium is an important tool to have in your toolkit. Selenium is widely used for automating user interactions like clicking buttons, filling out the f
7 min read
How to Add Blocked Extension on Chrome? Google Chrome extensions are small software programs that enhance the browsing experience. Thousands of extensions are available in the Chrome Web Store, where users can find easy solutions to streamline tasks, improve efficiency, and personalize their online experience. Besides this, extensions of
3 min read