""" 备注: 浏览器断点调试,不需要每次都要重新跑 函数实现 """ import os from selenium import webdriver from selenium.webdriver.chrome.options import Options import socket # 单独打开浏览器,使用9222端口,信息保存到E:/pythonwork/testfile # 请在这个浏览器下面安装xpath-help儿插件 driver = None def debug_browser(): global driver ip = '127.0.0.1' port = 5003 user_file = 'E:/Py_selenium/auto/' chrome_option = Options() """ 判断调试端口是否监听 :return:check 是否监听 """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex((ip, port)) if result == 0: check = True else: check = False sock.close() """ :return: chrome_option 浏览器调试选项 """ # 判断是否已经启动调试端口,已启动直接添加监听选项 if check: chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(ip, port)) # 未启动则重新启动浏览器并监听调试端口 else: os.popen('cd C:/Users/antony/AppData/Local/Google/Chrome/Application/ & chrome.exe --remote-debugging-port="{}" --user-data-dir="{}"'.format(port, user_file)) chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(ip, port)) return chrome_option # 使用方法 # 如果在该端口存在浏览器,直接使用该浏览器启动driver # 如果不存在,则在端口打开浏览器,然后再在该端口启动driver #if __name__ == '__main__': driver=webdriver.Chrome(options=debug_browser()) driver.get('https://www.baidu.com') #driver.get('https://www.qq.com')