通过 Selenium 在 Chrome 上打开检查(按 F12)

Opening inspect (pressing F12) on Chrome via Selenium

我可以通过 Selenium 打开 Chrome,但无法模拟按键(特别是 F12,因为我想打开 Inspect 并最终使用移动浏览器 Like so),而我我可以手动完成,即打开 Chrome 并按 F12,我希望能够使用 Selenium 自动化这部分。我当前的代码如下所示 -

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()

虽然代码运行没有任何错误,但我没有看到在浏览器上打开检查。任何建议和帮助表示赞赏!先感谢您。

模拟 F12 的按键类似于打开

要打开 google-chrome-devtoolschrome-browser-console 你必须使用 ChromeOptions class 添加参数 --auto-open-devtools-for-tabs参数如下:

  • 代码块:

    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)
    
  • 控制台输出:

    The Selenium Browser Automation Project :: Documentation for Selenium
    
  • 浏览器控制台快照:

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

因为我无法添加评论,所以只是写作为其他人的新答案。刚刚使用最新的 Chrome 驱动程序 (100.0.4896) 和 Python 3.7 进行了尝试——以下也能正常工作。

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://whosebug.com/"
driver.get(home_page_url)