2

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.

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
KRW4
  • 57
  • 8

1 Answers1

4

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?

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
  • Thank you! This was exactly what I was looking for. Do you know how I can programmatically open/toggle device toolbar to select say iPhone whenever I open? I'm trying to simulate key press of Command + Shift + M, but it doesn't seem to be doing the trick. – KRW4 Dec 18 '19 at 04:56
  • @KRW4 Not sure about that. If you can raise a new question I can have a go at your new usecase. – DebanjanB Dec 18 '19 at 10:58
  • Is it possible to get it to the console tab. The Element tab is rather useless for documenting errors. thanks – MortenB Jun 11 '20 at 07:54
  • 1
    @MortenB All the functionalities of _Console_ tab probably would be available programatically in Selenium v4.x – DebanjanB Jun 11 '20 at 08:03