0


python selenium 通过端口关闭进程

def selenium_login():
    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    options = Options()
    # options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    driver = webdriver.Chrome(options=options)
    print('caps:', driver.caps)
    debugger_address = driver.caps['goog:chromeOptions']['debuggerAddress']
    print('debugger_address:', debugger_address)
    debug_host, debug_port = driver.caps['goog:chromeOptions']['debuggerAddress'].split(':')
    with open('debug_port.txt', 'w', encoding='utf-8') as f:
        f.write(debug_port + '\n')
def kill_port():
    import os
    import subprocess
    """根据端口号杀死对应的进程"""
    if os.path.exists('debug_port.txt'):
        with open('debug_port.txt', 'r', encoding='utf-8') as f:
            port = f.read().strip()
    else:
        return
    # 根据端口号查询pid
    find_port = 'netstat -aon | findstr %s' % port
    process = subprocess.Popen(find_port, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding="gbk", shell=True)
    text = process.stdout.read()
    # 提取pid
    text = [i.split(' ') for i in text.split('\n') if i]
    pids = []
    for i in text:
        pid = [u for u in i if u]
        if str(port) in pid[1]:
            pids.append(pid[-1])
    pids = list(set(pids))
    # 杀死占用端口的pid
    for pid in pids:
        find_kill = 'taskkill -f -pid %s' % pid
        subprocess.Popen(find_kill)
def kill_port():
    import os
    import subprocess
    import psutil
    """根据端口号杀死对应的进程"""
    if os.path.exists('debug_port.txt'):
        with open('debug_port.txt', 'r', encoding='utf-8') as f:
            port = f.read().strip()
    else:
        return
    port_pid = {}
    for i in psutil.net_connections():
        pid = i.pid
        status = i.status
        port = i.laddr.port
        port_pid[port] = pid
    # 关闭占用端口的pid
    if port_pid.get(int(port)):
        find_kill = 'taskkill -f -pid %s' % port_pid[int(port)]
        subprocess.Popen(find_kill)
标签: python selenium chrome

本文转载自: https://blog.csdn.net/lwdfzr/article/details/130302802
版权归原作者 FOAF-lambda 所有, 如有侵权,请联系我们删除。

“python selenium 通过端口关闭进程”的评论:

还没有评论