Skip to content

Using existing event loop #3721

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mrwillis opened this issue May 1, 2025 · 3 comments
Closed

Using existing event loop #3721

mrwillis opened this issue May 1, 2025 · 3 comments
Labels
duplicate The answer/solution already exists somewhere question Someone is looking for answers UC Mode / CDP Mode Undetected Chromedriver Mode / CDP Mode

Comments

@mrwillis
Copy link

mrwillis commented May 1, 2025

Hi there,

I am trying to use the context manager like so

def join_google_meet():
    logging.info("Starting Google Meet session")
    with SB(uc=True, headless=True, window_size="1920,1080", undetected=True) as sb:
        logging.info("Initialized SeleniumBase")
        sb.activate_cdp_mode()
        logging.info("Activated CDP mode")
        sb.sleep(5)
        sb.save_screenshot_to_logs("screenshot.png")
async def main():
    try:
        # Setup audio before joining the meeting
        await setup_audio()
        join_google_meet()
    except Exception as e:
        logging.error(f"An error occurred: {str(e)}", exc_info=True)
        raise

if __name__ == "__main__":
    asyncio.run(main())

but I'm getting this error, presumably because of competing event loops

2025-05-01 14:55:13,550 - INFO - Initialized SeleniumBase
2025-05-01 14:55:16,275 - ERROR - An error occurred: Cannot run the event loop while another loop is running
Traceback (most recent call last):
  File "/app/index.py", line 140, in main
    join_google_meet()
  File "/app/index.py", line 71, in join_google_meet
    sb.activate_cdp_mode()
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/fixtures/base_case.py", line 4882, in activate_cdp_mode
    self.driver.uc_open_with_cdp_mode(url, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/core/browser_launcher.py", line 5431, in <lambda>
    lambda *args, **kwargs: uc_open_with_cdp_mode(
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/core/browser_launcher.py", line 561, in uc_open_with_cdp_mode
    driver.cdp_base = loop.run_until_complete(
  File "/usr/lib/python3.10/asyncio/base_events.py", line 625, in run_until_complete
    self._check_running()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 586, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
Traceback (most recent call last):
  File "/app/index.py", line 146, in <module>
    asyncio.run(main())
  File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/app/index.py", line 140, in main
    join_google_meet()
  File "/app/index.py", line 71, in join_google_meet
    sb.activate_cdp_mode()
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/fixtures/base_case.py", line 4882, in activate_cdp_mode
    self.driver.uc_open_with_cdp_mode(url, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/core/browser_launcher.py", line 5431, in <lambda>
    lambda *args, **kwargs: uc_open_with_cdp_mode(
  File "/usr/local/lib/python3.10/dist-packages/seleniumbase/core/browser_launcher.py", line 561, in uc_open_with_cdp_mode
    driver.cdp_base = loop.run_until_complete(
  File "/usr/lib/python3.10/asyncio/base_events.py", line 625, in run_until_complete
    self._check_running()
  File "/usr/lib/python3.10/asyncio/base_events.py", line 586, in _check_running
    raise RuntimeError(
RuntimeError: Cannot run the event loop while another loop is running
sys:1: RuntimeWarning: coroutine 'start' was never awaited

Is there a way to give SeleniumBase an event loop that I can manage so I can do other async stuff? I've tried using

https://github.com/seleniumbase/SeleniumBase/blob/master/examples/cdp_mode/raw_async.py

but can't figure out how to enable UC mode.

@mdmintz mdmintz added duplicate The answer/solution already exists somewhere question Someone is looking for answers UC Mode / CDP Mode Undetected Chromedriver Mode / CDP Mode labels May 1, 2025
@mdmintz
Copy link
Member

mdmintz commented May 1, 2025

Duplicate of #3464 (comment)


If you're looking to use async/await with SeleniumBase CDP Mode, there's an async format. Eg:

import asyncio
import time
from seleniumbase.undetected import cdp_driver

async def main():
    driver = await cdp_driver.cdp_util.start_async()
    page = await driver.get("about:blank")
    await page.set_locale("en")
    await page.get("https://www.priceline.com/")
    time.sleep(3)
    print(await page.evaluate("document.title"))
    element = await page.select('[data-testid*="endLocation"]')
    await element.click_async()
    time.sleep(1)
    await element.send_keys_async("Boston")
    time.sleep(2)

if __name__ == "__main__":
    loop = asyncio.new_event_loop()
    loop.run_until_complete(main())

Otherwise, if you want nested event loops, see https://stackoverflow.com/a/61847103/7058266, which tells you to use nest_asyncio: (pip install nest-asyncio):

import nest_asyncio
nest_asyncio.apply()

@mdmintz mdmintz closed this as completed May 1, 2025
@mrwillis
Copy link
Author

mrwillis commented May 1, 2025

@mdmintz Okay great that seems to works, thanks. The issue I'm having now is that it seems the options are slightly different? I am trying to join a google meet call and with this code

 with SB(uc=True, headless=True) as sb:
        logging.info("Initialized SeleniumBase")
        sb.activate_cdp_mode()
        logging.info("Activated CDP mode")
        
        logging.info("Opening Google Meet URL")
        sb.open(url)

and it works fine. No detection. But with this code

    logging.info("Starting Google Meet session")
    driver = await cdp_driver.cdp_util.start_async(headless=True)
    try:
        logging.info("Initialized CDP driver")
        page = await page.get(url)
        logging.info("Opened Google Meet URL")
        
        time.sleep(5)
        logging.info("Saving screenshot")

I am getting this. Am I missing some options? I would presume the behaviour is exactly the same.

Image

@mdmintz
Copy link
Member

mdmintz commented May 1, 2025

Headless Mode is detectable, so I wouldn't expect it to work at all.
If you need to run on Linux, use Xvfb, which is included with UC Mode.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate The answer/solution already exists somewhere question Someone is looking for answers UC Mode / CDP Mode Undetected Chromedriver Mode / CDP Mode
Projects
None yet
Development

No branches or pull requests

2 participants