Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
fixed tests, now headless, no more asyncio errors (hopefully)
Gregor Žunič36fabb799c6d
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex cd0957094..f3f7a480f 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -116,21 +116,19 @@ class BrowserContext:await self.save_cookies()- session = await self.get_session()- await session.context.close()+ await self.session.context.close()def __del__(self):- """Async cleanup when object is destroyed"""+ """Cleanup when object is destroyed"""if self.session is not None:+ logger.debug('BrowserContext was not properly closed before destruction')try:- loop = asyncio.get_running_loop()- if loop.is_running():- loop.create_task(self.close())- else:- asyncio.run(self.close())- except RuntimeError:- # No event loop running- asyncio.run(self.close())+ # Use sync Playwright method for force cleanup+ if hasattr(self.session.context, '_impl_obj'):+ self.session.context._impl_obj.close()+ self.session = None+ except Exception as e:+ logger.warning(f'Failed to force close browser context: {e}')async def _initialize_session(self):"""Initialize the browser session"""diff --git a/tests/test_agent_actions.py b/tests/test_agent_actions.pyindex 4f18badc3..d0118229c 100644--- a/tests/test_agent_actions.py+++ b/tests/test_agent_actions.py@@ -1,3 +1,4 @@+import asyncioimport osimport pytest@@ -6,14 +7,9 @@ from pydantic import BaseModel, SecretStrfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryList+from browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.browser.views import BrowserState-# browser = Browser(-# config=BrowserConfig(-# # headless=False,-# )-# )-@pytest.fixturedef llm():@@ -29,20 +25,41 @@ def llm():# return ChatOpenAI(model='gpt-4o-mini')-# @pytest.fixture-# async def context():-# async with await browser.new_context() as context:-# yield context[email protected](scope='session')+def event_loop():+ """Create an instance of the default event loop for each test case."""+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++[email protected](scope='session')+async def browser(event_loop):+ browser_instance = Browser(+ config=BrowserConfig(+ headless=True,+ )+ )+ yield browser_instance+ await browser_instance.close()+++async def context(browser):+ async with await browser.new_context() as context:+ yield context+ # Clean up automatically happens with __aexit__# pytest tests/test_agent_actions.py -v -k "test_ecommerce_interaction" --capture=no# @pytest.mark.asyncio@pytest.mark.skip(reason='Kinda expensive to run')-async def test_ecommerce_interaction(llm):+async def test_ecommerce_interaction(llm, context):"""Test complex ecommerce interaction sequence"""agent = Agent(task="Go to amazon.com, search for 'laptop', filter by 4+ stars, and find the price of the first result",llm=llm,+ browser_context=context,save_conversation_path='tmp/test_ecommerce_interaction/conversation',)@@ -75,11 +92,12 @@ async def test_ecommerce_interaction(llm):# @pytest.mark.asyncio-async def test_error_recovery(llm):+async def test_error_recovery(llm, context):"""Test agent's ability to recover from errors"""agent = Agent(task='Navigate to nonexistent-site.com and then recover by going to google.com ',llm=llm,+ browser_context=context,)history: AgentHistoryList = await agent.run(max_steps=10)@@ -99,11 +117,12 @@ async def test_error_recovery(llm):# @pytest.mark.asyncio-async def test_find_contact_email(llm):+async def test_find_contact_email(llm, context):"""Test agent's ability to find contact email on a website"""agent = Agent(task='Go to https://browser-use.com/ and find out the contact email',llm=llm,+ browser_context=context,)history: AgentHistoryList = await agent.run(max_steps=10)@@ -119,11 +138,12 @@ async def test_find_contact_email(llm):# @pytest.mark.asyncio-async def test_agent_finds_installation_command(llm):+async def test_agent_finds_installation_command(llm, context):"""Test agent's ability to find the pip installation command for browser-use on the web"""agent = Agent(task='Find the pip installation command for the browser-use repo',llm=llm,+ browser_context=context,)history: AgentHistoryList = await agent.run(max_steps=10)@@ -176,30 +196,29 @@ class CaptchaTest(BaseModel):),],)-async def test_captcha_solver(llm, captcha: CaptchaTest):+async def test_captcha_solver(llm, context, captcha: CaptchaTest):"""Test agent's ability to solve different types of captchas"""- async with await browser.new_context() as context:- agent = Agent(- task=f'Go to {captcha.url} and solve the captcha. {captcha.additional_text}',- llm=llm,- browser_context=context,- )- from browser_use.agent.views import AgentHistoryList+ agent = Agent(+ task=f'Go to {captcha.url} and solve the captcha. {captcha.additional_text}',+ llm=llm,+ browser_context=context,+ )+ from browser_use.agent.views import AgentHistoryList- history: AgentHistoryList = await agent.run(max_steps=7)+ history: AgentHistoryList = await agent.run(max_steps=7)- state: BrowserState = await context.get_state()+ state: BrowserState = await context.get_state()- all_text = state.element_tree.get_all_text_till_next_clickable_element()+ all_text = state.element_tree.get_all_text_till_next_clickable_element()- if not all_text:- all_text = ''+ if not all_text:+ all_text = ''- if not isinstance(all_text, str):- all_text = str(all_text)+ if not isinstance(all_text, str):+ all_text = str(all_text)- solved = captcha.success_text in all_text- assert solved, f'Failed to solve {captcha.name}'+ solved = captcha.success_text in all_text+ assert solved, f'Failed to solve {captcha.name}'# python -m pytest tests/test_agent_actions.py -v --capture=nodiff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.pyindex 76d8588cc..5034ea6ea 100644--- a/tests/test_core_functionality.py+++ b/tests/test_core_functionality.py@@ -1,3 +1,4 @@+import asyncioimport osimport pytest@@ -8,18 +9,35 @@ from browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryListfrom browser_use.browser.browser import Browser, BrowserConfig-browser = Browser(- config=BrowserConfig(- # headless=False,+[email protected](scope='session')+def event_loop():+ """Create an instance of the default event loop for each test case."""+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++[email protected](scope='session')+async def browser(event_loop):+ browser_instance = Browser(+ config=BrowserConfig(+ headless=True,+ ))-)+ yield browser_instance+ await browser_instance.close()+++async def context(browser):+ async with await browser.new_context() as context:+ yield context@pytest.fixturedef llm():"""Initialize language model for testing"""-- # return ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)return AzureChatOpenAI(model='gpt-4o',api_version='2024-10-21',@@ -29,12 +47,6 @@ def llm():# pytest -s -k test_search_google-async def context():- async with await browser.new_context() as context:- yield context--@pytest.mark.asyncioasync def test_search_google(llm, context):"""Test 'Search Google' action"""diff --git a/tests/test_mind2web.py b/tests/test_mind2web.pyindex e4fc1ae15..1bbd3c907 100644--- a/tests/test_mind2web.py+++ b/tests/test_mind2web.py@@ -2,6 +2,7 @@Test browser automation using Mind2Web dataset tasks with pytest framework."""+import asyncioimport jsonimport osfrom typing import Any, Dict, List@@ -18,11 +19,29 @@ from browser_use.utils import loggerMAX_STEPS = 50TEST_SUBSET_SIZE = 10-browser = Browser(- config=BrowserConfig(- # headless=False,+[email protected](scope='session')+def event_loop():+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++[email protected](scope='session')+async def browser(event_loop):+ browser_instance = Browser(+ config=BrowserConfig(+ headless=True,+ ))-)+ yield browser_instance+ await browser_instance.close()+++async def context(browser):+ async with await browser.new_context() as new_context:+ yield new_context@pytest.fixture(scope='session')@@ -52,13 +71,6 @@ def llm():)-# @pytest.fixture(scope='function')-async def context():- async with await browser.new_context() as context:- yield context--# run with: pytest -s -v tests/test_mind2web.py:test_random_samples@pytest.mark.asyncioasync def test_random_samples(test_cases: List[Dict[str, Any]], llm, context, validator):diff --git a/tests/test_self_registered_actions.py b/tests/test_self_registered_actions.pyindex 8fd54a0d7..2221f7866 100644--- a/tests/test_self_registered_actions.py+++ b/tests/test_self_registered_actions.py@@ -1,3 +1,4 @@+import asyncioimport osimport pytest@@ -6,9 +7,34 @@ from pydantic import BaseModel, SecretStrfrom browser_use.agent.service import Agentfrom browser_use.agent.views import AgentHistoryList+from browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.controller.service import Controller[email protected](scope='session')+def event_loop():+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++[email protected](scope='session')+async def browser(event_loop):+ browser_instance = Browser(+ config=BrowserConfig(+ headless=True,+ )+ )+ yield browser_instance+ await browser_instance.close()+++async def context(browser):+ async with await browser.new_context() as context:+ yield context++@pytest.fixtureasync def controller():"""Initialize the controller with self-registered actions"""diff --git a/tests/test_stress.py b/tests/test_stress.pyindex ec85e471f..07a5e8fab 100644--- a/tests/test_stress.py+++ b/tests/test_stress.py@@ -1,3 +1,4 @@+import asyncioimport osimport randomimport string@@ -11,11 +12,29 @@ from browser_use.agent.service import Agentfrom browser_use.browser.browser import Browser, BrowserConfigfrom browser_use.controller.service import Controller-browser = Browser(- config=BrowserConfig(- # headless=False,+[email protected](scope='session')+def event_loop():+ loop = asyncio.get_event_loop_policy().new_event_loop()+ yield loop+ loop.close()++[email protected](scope='session')+async def browser(event_loop):+ browser_instance = Browser(+ config=BrowserConfig(+ headless=True,+ ))-)+ yield browser_instance+ await browser_instance.close()+++async def context(browser):+ async with await browser.new_context() as context:+ yield context@pytest.fixture@@ -30,12 +49,6 @@ def llm():return model-async def context():- async with await browser.new_context() as context:- yield context--def generate_random_text(length: int) -> str:"""Generate random text of specified length"""return ''.join(random.choices(string.ascii_letters + string.digits + ' ', k=length))@@ -55,33 +68,31 @@ async def controller():@pytest.mark.asyncio-async def test_token_limit_with_multiple_extractions(llm, controller):+async def test_token_limit_with_multiple_extractions(llm, controller, context):"""Test handling of multiple smaller extractions accumulating tokens"""-agent = Agent(task='Call the magical function to get very special text 5 times',llm=llm,controller=controller,+ browser_context=context,max_input_tokens=2000,save_conversation_path='tmp/stress_test/test_token_limit_with_multiple_extractions.json',)history = await agent.run(max_steps=5)- # ckeck if 5 times called get_special_text+ # check if 5 times called get_special_textcalls = [a for a in history.action_names() if a == 'get_very_special_text']assert len(calls) == 5# check the message history should be max 3 messagesassert len(agent.message_manager.history.messages) > 3-# should get rate limited@pytest.mark.slow@pytest.mark.parametrize('max_tokens', [4000]) # 8000 20000@pytest.mark.asyncioasync def test_open_3_tabs_and_extract_content(llm, controller, context, max_tokens):"""Stress test: Open 3 tabs with urls and extract content"""- # NOTE: currently we first remove the oldest messages, so the model forgets what it has done already and fails most likely long term tasks - so dont put too much attention to this testagent = Agent(task='Open 3 tabs with https://en.wikipedia.org/wiki/Internet and extract the content from each.',llm=llm,