Open In App

How to Add Chrome Extension using Python Selenium

Last Updated : 09 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. Create new Directory - In which we will have all our extension files
  2. Create a Manifest File - This will be used describe the Extension like Name, version
  3. Create Html File - This will be used to design the interface to show to the user.
  4. Create Javascript file - This will be used to write logical code.
  5. 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.

  1. Keep Tools Updated: Always have the latest version of Chrome Driver, Chrome browser, and Selenium.
  2. Have Virtual Environments: We generally use virtual environment for avoiding dependencies conflicts.
  3. 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.


Next Article
Practice Tags :

Similar Reads