Get PID of Browser launched by selenium

前端 未结 9 1555
闹比i
闹比i 2020-11-30 07:15

I would like to get the PID of the browser launched by selenium. Is there any way to get it done?

9条回答
  •  情深已故
    2020-11-30 08:14

    You can retrieve the PID of Browser Process launched by Selenium using python client in different ways as follows:


    Firefox

    Accessing the capabilities object which returns a dictionary using the following solution:

    • Code Block:

      from selenium import webdriver
      from selenium.webdriver.firefox.options import Options
      
      options = Options()
      options.binary_location = r'C:\Program Files\Firefox Nightly\firefox.exe'
      driver = webdriver.Firefox(firefox_options=options, executable_path=r'C:\WebDrivers\geckodriver.exe')
      my_dict = driver.capabilities
      print("PID of the browser process is: " + str(my_dict['moz:processID']))
      
    • Console Output:

      PID of the browser process is: 14240
      
    • Browser Snapshot:


    Chrome

    Iterating through the processes using psutil.process_iter() where process.cmdline() contains --test-type=webdriver as follows:

    • Code Block:

      from selenium import webdriver
      from contextlib import suppress
      import psutil
      
      driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
      driver.get('https://www.google.com/')
      for process in psutil.process_iter():
          if process.name() == 'chrome.exe' and '--test-type=webdriver' in process.cmdline():
          with suppress(psutil.NoSuchProcess):
              print(process.pid)
      
    • Console Output:

      1164
      1724
      4380
      5748        
      
    • Browser Snapshot:

提交回复
热议问题