'Opening inspect (pressing F12) on Chrome via Selenium

I am able to open Chrome via Selenium, but am unable to simulate a key press (specifically F12, since I want to open Inspect and eventually use the mobile browser Like so) While I'm able to do it manually i.e, open Chrome and press F12, I want to be able to automate this part using Selenium. My current code looks like this -

from selenium import webdriver
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument("--test-type")
options.binary_location = "/usr/bin/chromium"
driver = webdriver.Chrome('/Users/amigo/Documents/pet_projects/selenium/chromedriver')
driver.get('https://www.google.com')
ActionChains(driver).send_keys(Keys.F12).perform()

While the code runs without any errors, I do not see the inspect being opened on the browser. Any suggestions and help appreciated! Thank you in advance.



Solution 1:[1]

Simulating the key press for F12 resembles to opening the .

To open the google-chrome-devtools i.e. the chrome-browser-console you have to use the ChromeOptions class to add the argument --auto-open-devtools-for-tabs argument as follows:

  • Code Block:

    from selenium import webdriver
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument("--auto-open-devtools-for-tabs")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("https://selenium.dev/documentation/en/")
    print(driver.title)
    
  • Console Output:

    The Selenium Browser Automation Project :: Documentation for Selenium
    
  • Browser Console Snapshot:

chrome-dev-tools

You can find a relevant based discussion in How to open Chrome browser console through Selenium?

Solution 2:[2]

As I can not add a comment, just writing as a new answer for others. Just tried that with latest Chrome Driver (100.0.4896) and Python 3.7 -- following is working as well.

from selenium import webdriver
options = webdriver.ChromeOptions() 
options.add_argument("--auto-open-devtools-for-tabs")

driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
home_page_url = "https://stackoverflow.com/"
driver.get(home_page_url)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2