python使用selenium進行瀏覽器中途調試的方法


1、檢查9222端口是否已經啟動瀏覽器
2、如已啟動就返回chrome_option
3、如未啟動則打開瀏覽器,保存配置文件到E:/pythonwork/testfile,並監聽9222端口,返回chrome_option


import os
from selenium.webdriver.chrome.options import Options
import socket


# 單獨打開瀏覽器,使用9222端口,信息保存到E:/pythonwork/testfile
# 請在這個瀏覽器下面安裝xpath-help兒插件
class DebugBrowser:
    def __init__(self):
        self.ip = '127.0.0.1'
        self.port = 9222
        self.userfile = 'E:/pythonwork/testfile'
        self.chrome_option = Options()

    def debug_chrome(self):
        """
        :return: chrome_option 瀏覽器調試選項
        """
        # 判斷是否已經啟動調試端口,已啟動直接添加監聽選項
        if self.check_port():
            self.chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(self.ip, self.port))
        # 未啟動則重新啟動瀏覽器並監聽調試端口
        else:
            os.popen('cd C:/Users/yasin/AppData/Local/Google/Chrome/Application'
                     ' && chrome.exe --remote-debugging-port={} --user-data-dir="{}"'.format(self.port, self.user_file))
            self.chrome_option.add_experimental_option('debuggerAddress', '{}:{}'.format(self.ip,  self.port))
        return self.chrome_option

    def check_port(self):
        """
        判斷調試端口是否監聽
        :return:check 是否監聽
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((self.ip, self.port))
        if result == 0:
            check = True
        else:
            check = False
        sock.close()
        return check
  
#  使用方法
#  如果在該端口存在瀏覽器,直接使用該瀏覽器啟動driver
#  如果不存在,則在端口打開瀏覽器,然后再在該端口啟動driver
driver=webdriver.Chrome(options=DebugBrowser().debug_chrome())

 

轉載請注明出處

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM