在Selenium中检查是否存在已打开特定端口的Chrome实例,可以通过以下步骤进行:
from selenium import webdriver
import socket
def is_port_open(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', port))
sock.close()
return result == 0
port = 8888 # 指定要检查的端口号
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'--remote-debugging-port={port}')
driver = webdriver.Chrome(options=chrome_options)
if is_port_open(port):
print(f'端口 {port} 已被占用')
else:
print(f'端口 {port} 未被占用')
完整的代码示例:
from selenium import webdriver
import socket
def is_port_open(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', port))
sock.close()
return result == 0
port = 8888 # 指定要检查的端口号
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(f'--remote-debugging-port={port}')
driver = webdriver.Chrome(options=chrome_options)
if is_port_open(port):
print(f'端口 {port} 已被占用')
else:
print(f'端口 {port} 未被占用')
这样,你就可以使用Selenium在Python中检查特定端口是否已被Chrome实例占用了。
领取专属 10元无门槛券
手把手带您无忧上云