Get PID of Browser launched by selenium

前端 未结 9 1509
闹比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:07

    If you're using PhantomJS then you can get the PID from the process Popen object:

    from selenium import webdriver
    browser = webdriver.PhantomJS()
    print browser.service.process.pid  
    
    0 讨论(0)
  • 2020-11-30 08:14

    Using the Python API, it's pretty simple:

    from selenium import webdriver
    browser = webdriver.Firefox()
    print browser.binary.process.pid
    # browser.binary.process is a Popen object...
    

    If you're using Chrome, it's a little more complex, you go via a chromedriver process:

    c = webdriver.Chrome()
    c.service.process # is a Popen instance for the chromedriver process
    import psutil
    p = psutil.Process(c.service.process.pid)
    print p.get_children(recursive=True)
    
    0 讨论(0)
  • 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:

    0 讨论(0)
提交回复
热议问题