Search code examples
pythonchromium

How can i switch multiple chrome profiles by their names in DrissionPage ChromiumPage?


My current code doesn't switch from one profile to other

from DrissionPage import ChromiumOptions, ChromiumPage,Chromium
co = ChromiumOptions()
co.set_user(user='event_name1')
page = ChromiumPage(co)
co = ChromiumOptions()
co.set_user(user='event_name2')
page = ChromiumPage(co)

Solution

  • from DrissionPage import Chromium
    from concurrent.futures import ThreadPoolExecutor, as_completed
    
    # Dictionary of event links
    event_links = {
        '1': 'http://drissionpage.cn/browser_control/mode_change/',
        '2': 'https://DrissionPage.cn',
        '3': 'https://example.com'
    }
    
    # Predefined Chromium instances with specific debugging ports
    browsers = {
        '1': Chromium(9222),  # Browser 1 on port 9222
        '2': Chromium(9333),  # Browser 2 on port 9333
        '3': Chromium(9444)   # Browser 3 on port 9444
    }
    
    # Function to open a URL in a specific browser instance
    def open_browser(args):
        session_id, url = args  # Unpack session ID and URL
    
        # Retrieve the associated browser instance
        browser = browsers[session_id]
        tab = browser.latest_tab  
        # Navigate the browser to the target URL
        tab.get(url)
        print(f"Browser session {session_id} opened for URL: {url}")
        
        return session_id, url
    
    # Main function to manage concurrent browser sessions
    def main():
        # Use ThreadPoolExecutor for concurrent execution
        with ThreadPoolExecutor(max_workers=len(event_links)) as executor:
            # Submit tasks for each session (key, URL pair)
            futures = {executor.submit(open_browser, (key, url)): (key, url) for key, url in event_links.items()}
            
            # Process results as they are completed
            for future in as_completed(futures):
                try:
                    session_id, url = future.result()  # Retrieve session ID and URL
                    print(f"Session {session_id} completed for URL: {url}")
                except Exception as e:
                    print(f"Error in session: {e}")
    
    # Run the script
    if __name__ == "__main__":
        main()