[英]Python Selenium: Extracting the PID of Chrome and Firefox browser
How do you get the process ID (PID) of the Chrome/Chromium or Firefox browser launched by Selenium?如何获取Selenium启动的Chrome/Chromium或Firefox浏览器的进程ID(PID)? I'm looking for a solution that also works when the browser is launched in a Selenium Grid.我正在寻找一种在 Selenium Grid 中启动浏览器时也能工作的解决方案。
Using driver.service.process.pid
is not possible with Selenium Grid. Selenium Grid 无法使用driver.service.process.pid
。
To retrieve the process ID (PID) of the Chrome/Firefox browsers launched by Selenium you can use the following solutions:要检索Selenium启动的 Chrome/Firefox 浏览器的进程 ID (PID) ,您可以使用以下解决方案:
Code Block:代码块:
from selenium import webdriver driver = webdriver.Firefox(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: 2172
Code Block:代码块:
from selenium import webdriver from contextlib import suppress import psutil driver = webdriver.Chrome(executable_path=r'C:\\WebDrivers\\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) driver.quit()
Console Output:控制台输出:
12384 13656 13800
You can find a couple of relevant detailed discussions in:您可以在以下位置找到一些相关的详细讨论:
When launching a browser with Selenium, it creates a new temporary directory for the profile settings (unless otherwise specified).使用 Selenium 启动浏览器时,它会为配置文件设置创建一个新的临时目录(除非另有说明)。 We can use this to identify the specific process(es) that the browser uses:我们可以使用它来识别浏览器使用的特定进程:
In [470]: driver.capabilities
Out[470]:
{'acceptInsecureCerts': False,
'browserName': 'chrome',
'browserVersion': '86.0.4240.198',
'chrome': {'chromedriverVersion': '85.0.4183.87 (cd6713ebf92fa1cacc0f1a598df280093af0c5d7-refs/branch-heads/4183@{#1689})',
'userDataDir': '/tmp/.com.google.Chrome.nW2W6p'},
'goog:chromeOptions': {'debuggerAddress': 'localhost:44047'},
...}
This approach works for both Firefox and Chrome, even if you have multiple instances of a browser running, and also if the browsers are launched through Selenium Grid (if the code is run on the node server).这种方法适用于 Firefox 和 Chrome,即使您有多个浏览器实例正在运行,并且如果浏览器是通过 Selenium Grid 启动的(如果代码在节点服务器上运行)。
You will need to install psutil
:您将需要安装psutil
:
pip install psutil
import psutil
import re
from typing import List
def pgrep(term, regex=False, full=True) -> List[psutil.Process]:
"""
If `full`, then `term` is matched against the command line
the process has been called with,
else it is only matched against the process name.
"""
procs = []
for proc in psutil.process_iter(['pid', 'name', 'username', 'cmdline']):
if full:
name = ' '.join(proc.cmdline())
else:
name = proc.name()
try:
if regex and re.search(term, name):
procs.append(proc)
elif term in name:
procs.append(proc)
except psutil.NoSuchProcess:
pass
return procs
def browser_procs(driver) -> List[psutil.Process]:
"""
Return the Processes associated with the browser
(excluding geckodriver/chromedriver)
"""
if driver.capabilities['browserName'] == 'firefox':
directory = driver.capabilities['moz:profile']
else:
directory = driver.capabilities['chrome']['userDataDir']
procs = pgrep(directory, full=True)
procs.sort(key=lambda p: p.pid)
return procs
def browser_proc(driver) -> psutil.Process:
"""
Return the main Process of the browser
(excluding geckodriver/chromedriver)
"""
procs = browser_procs(driver)
for proc in procs:
name = proc.parent().name()
if 'chromedriver' in name or 'geckodriver' in name:
return proc
raise ValueError
def driver_proc(driver) -> psutil.Process:
"""
Return the Process of the geckodriver/chromedriver
"""
return browser_proc(driver).parent()
Let's see it in action:让我们看看它的实际效果:
In [436]: driver = Chrome()
In [451]: browser_procs(driver)
Out[468]:
[psutil.Process(pid=38453, name='chrome', status='sleeping', started='18:45:51'),
psutil.Process(pid=38462, name='chrome', status='sleeping', started='18:45:51'),
psutil.Process(pid=38463, name='chrome', status='sleeping', started='18:45:51'),
psutil.Process(pid=38467, name='chrome', status='sleeping', started='18:45:51'),
psutil.Process(pid=38486, name='chrome', status='sleeping', started='18:45:52'),
psutil.Process(pid=38489, name='chrome', status='sleeping', started='18:45:52'),
psutil.Process(pid=38521, name='chrome', status='sleeping', started='18:45:52'),
psutil.Process(pid=38522, name='chrome', status='sleeping', started='18:45:52')]
In [471]: p = browser_proc(driver)
In [472]: p.pid
Out[472]: 38453
If you want the PID of the chromedriver or geckodriver, then you can get that process through browser_proc(driver).parent()
如果您想要 chromedriver 或 geckodriver 的 PID,那么您可以通过browser_proc(driver).parent()
获取该进程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.