Search code examples
pythonselenium-webdriverselenium-chromedrivermetamask

Selenium webdriver doesn't work with metamask


Here is my issue: I download Metamask extension and add it to Chrome. Then I start selenium webdriver, then I'm being redirected to the extension page, and when I try to click "I agree to Metamask terms", it simply does nohting. Webdriver doesn't even see the element. What do I do? (Don't mind the Brave browser below. Chromdriver shows the same thing)

Starting extension page

Setup: Pyhton 3.10.6, Chrome and Chromedriver 115, Linux Mint, Metamask extension 10.34.2

Code:

import time
import os
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import requests
import shutil


if __name__ == '__main__':
    # Downloading Metamask extension
    file_path = os.getcwd()
    url = "https://github.com/MetaMask/metamask-extension/releases/download/v10.34.2/metamask-chrome-10.34.2.zip"
    local_filename = file_path + '/' + url.split('/')[-1]

    with requests.get(url, stream=True) as r:
        with open(local_filename, 'wb') as f:
            shutil.copyfileobj(r.raw, f)


    # Chrome options configuration
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_argument('--ignore-certificate-errors-spki-list')
    chrome_options.add_argument('--ignore-certificate-errors')
    chrome_options.add_argument('--ignore-ssl-errors')
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument("--disable-blink-features=BlockCredentialedSubresources")
    chrome_options.add_argument("--disable-gpu")
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_argument("--disable-setuid-sandbox")
    chrome_options.add_argument("--disable-infobars")
    chrome_options.add_argument('--disable-software-rasterizer')
    # Adding extension to Chrome
    chrome_options.add_extension("metamask-chrome-10.34.2.zip")
    # Location to the Chrome binary (for Linux)     
    chrome_options.binary_location = "/usr/bin/google-chrome-stable"
    s = Service(
        executable_path='MY_FULL_EXECUTABLE_PATH'
    )
    driver = webdriver.Chrome(
        service=s,
        options=chrome_options
    )
    # Waiting 8 seconds for a page to download fully
    time.sleep(8)
    # The "I agree to Metamask terms" checkbox I want to click
    metamask_checkbox = driver.find_element(By.CSS_SELECTOR, '#onboarding__terms-checkbox')
    metamask_checkbox.click()
    time.sleep(5)
    driver.quit()

Solution

  • On Metamask extension on chrome browser the .click() function doesn't work. for each click on checkboxes or buttons you can use .send_keys(Keys.ENTER) instead. import Keys before use:

    from selenium.webdriver.common.keys import Keys
    
    metamask_checkbox.send_keys(Keys.ENTER)