Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

migrate old style tests

Nick Sweeting6cb1dbfac836
diff --git a/tests/extraction_test.py b/tests/extraction_test.py
index 250dbd191..b3f085b41 100644
--- a/tests/extraction_test.py
+++ b/tests/extraction_test.py
@@ -5,8 +5,7 @@ import anyio
from langchain_openai import ChatOpenAI
from browser_use.agent.prompts import AgentMessagePrompt
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext, BrowserContextConfig
+from browser_use.browser import BrowserProfile, BrowserSession
from browser_use.dom.service import DomService
@@ -48,18 +47,14 @@ DEFAULT_INCLUDE_ATTRIBUTES = [
async def test_focus_vs_all_elements():
- config = BrowserContextConfig(
- # cookies_file='cookies3.json',
- disable_security=True,
- wait_for_network_idle_page_load_time=1,
- )
-
- browser = Browser(
- config=BrowserConfig(
+ browser_session = BrowserSession(
+ browser_profile=BrowserProfile(
# executable_path='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ disable_security=True,
+ wait_for_network_idle_page_load_time=1,
+ headless=True,
)
)
- context = BrowserContext(browser=browser, config=config)
websites = [
'https://demos.telerik.com/kendo-react-ui/treeview/overview/basic/func?theme=default-ocean-blue-a11y',
@@ -81,100 +76,100 @@ async def test_focus_vs_all_elements():
'https://github.com',
]
- async with context as context:
- page = await context.get_current_page()
- dom_service = DomService(page)
+ await browser_session.start()
+ page = await browser_session.get_current_page()
+ dom_service = DomService(page)
+
+ for website in websites:
+ # sleep 2
+ await page.goto(website)
+ asyncio.sleep(1)
+
+ last_clicked_index = None # Track the index for text input
+ while True:
+ try:
+ print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')
+
+ # Get/refresh the state (includes removing old highlights)
+ print('\nGetting page state...')
+ all_elements_state = await browser_session.get_state_summary(True)
+
+ selector_map = all_elements_state.selector_map
+ total_elements = len(selector_map.keys())
+ print(f'Total number of elements: {total_elements}')
+
+ # print(all_elements_state.element_tree.clickable_elements_to_string())
+ prompt = AgentMessagePrompt(
+ browser_state_summary=all_elements_state,
+ result=None,
+ include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,
+ step_info=None,
+ )
+ # print(prompt.get_user_message(use_vision=False).content)
+ # Write the user message to a file for analysis
+ user_message = prompt.get_user_message(use_vision=False).content
+ os.makedirs('./tmp', exist_ok=True)
+ async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:
+ await f.write(user_message)
+
+ token_count, price = count_string_tokens(user_message, model='gpt-4o')
+ print(f'Prompt token count: {token_count}, price: {round(price, 4)} USD')
+ print('User message written to ./tmp/user_message.txt')
+
+ # also save all_elements_state.element_tree.clickable_elements_to_string() to a file
+ # with open('./tmp/clickable_elements.json', 'w', encoding='utf-8') as f:
+ # f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))
+ # print('Clickable elements written to ./tmp/clickable_elements.json')
+
+ answer = input("Enter element index to click, 'index,text' to input, or 'q' to quit: ")
+
+ if answer.lower() == 'q':
+ break
- for website in websites:
- # sleep 2
- await page.goto(website)
- asyncio.sleep(1)
-
- last_clicked_index = None # Track the index for text input
- while True:
try:
- print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')
-
- # Get/refresh the state (includes removing old highlights)
- print('\nGetting page state...')
- all_elements_state = await context.get_state_summary(True)
-
- selector_map = all_elements_state.selector_map
- total_elements = len(selector_map.keys())
- print(f'Total number of elements: {total_elements}')
-
- # print(all_elements_state.element_tree.clickable_elements_to_string())
- prompt = AgentMessagePrompt(
- browser_state_summary=all_elements_state,
- result=None,
- include_attributes=DEFAULT_INCLUDE_ATTRIBUTES,
- step_info=None,
- )
- # print(prompt.get_user_message(use_vision=False).content)
- # Write the user message to a file for analysis
- user_message = prompt.get_user_message(use_vision=False).content
- os.makedirs('./tmp', exist_ok=True)
- async with await anyio.open_file('./tmp/user_message.txt', 'w', encoding='utf-8') as f:
- await f.write(user_message)
-
- token_count, price = count_string_tokens(user_message, model='gpt-4o')
- print(f'Prompt token count: {token_count}, price: {round(price, 4)} USD')
- print('User message written to ./tmp/user_message.txt')
-
- # also save all_elements_state.element_tree.clickable_elements_to_string() to a file
- # with open('./tmp/clickable_elements.json', 'w', encoding='utf-8') as f:
- # f.write(json.dumps(all_elements_state.element_tree.__json__(), indent=2))
- # print('Clickable elements written to ./tmp/clickable_elements.json')
-
- answer = input("Enter element index to click, 'index,text' to input, or 'q' to quit: ")
-
- if answer.lower() == 'q':
- break
-
- try:
- if ',' in answer:
- # Input text format: index,text
- parts = answer.split(',', 1)
- if len(parts) == 2:
- try:
- target_index = int(parts[0].strip())
- text_to_input = parts[1]
- if target_index in selector_map:
- element_node = selector_map[target_index]
- print(
- f"Inputting text '{text_to_input}' into element {target_index}: {element_node.tag_name}"
- )
- await context._input_text_element_node(element_node, text_to_input)
- print('Input successful.')
- else:
- print(f'Invalid index: {target_index}')
- except ValueError:
- print(f'Invalid index format: {parts[0]}')
- else:
- print("Invalid input format. Use 'index,text'.")
- else:
- # Click element format: index
+ if ',' in answer:
+ # Input text format: index,text
+ parts = answer.split(',', 1)
+ if len(parts) == 2:
try:
- clicked_index = int(answer)
- if clicked_index in selector_map:
- element_node = selector_map[clicked_index]
- print(f'Clicking element {clicked_index}: {element_node.tag_name}')
- await context._click_element_node(element_node)
- print('Click successful.')
+ target_index = int(parts[0].strip())
+ text_to_input = parts[1]
+ if target_index in selector_map:
+ element_node = selector_map[target_index]
+ print(
+ f"Inputting text '{text_to_input}' into element {target_index}: {element_node.tag_name}"
+ )
+ await browser_session._input_text_element_node(element_node, text_to_input)
+ print('Input successful.')
else:
- print(f'Invalid index: {clicked_index}')
+ print(f'Invalid index: {target_index}')
except ValueError:
- print(f"Invalid input: '{answer}'. Enter an index, 'index,text', or 'q'.")
+ print(f'Invalid index format: {parts[0]}')
+ else:
+ print("Invalid input format. Use 'index,text'.")
+ else:
+ # Click element format: index
+ try:
+ clicked_index = int(answer)
+ if clicked_index in selector_map:
+ element_node = selector_map[clicked_index]
+ print(f'Clicking element {clicked_index}: {element_node.tag_name}')
+ await browser_session._click_element_node(element_node)
+ print('Click successful.')
+ else:
+ print(f'Invalid index: {clicked_index}')
+ except ValueError:
+ print(f"Invalid input: '{answer}'. Enter an index, 'index,text', or 'q'.")
- except Exception as action_e:
- print(f'Action failed: {action_e}')
+ except Exception as action_e:
+ print(f'Action failed: {action_e}')
- # No explicit highlight removal here, get_state handles it at the start of the loop
+ # No explicit highlight removal here, get_state handles it at the start of the loop
- except Exception as e:
- print(f'Error in loop: {e}')
- # Optionally add a small delay before retrying
- await asyncio.sleep(1)
+ except Exception as e:
+ print(f'Error in loop: {e}')
+ # Optionally add a small delay before retrying
+ await asyncio.sleep(1)
if __name__ == '__main__':
diff --git a/tests/test_attach_chrome.py b/tests/test_attach_chrome.py
deleted file mode 100644
index 2271f3f07..000000000
--- a/tests/test_attach_chrome.py
+++ /dev/null
@@ -1,69 +0,0 @@
-import asyncio
-
-from playwright.async_api import async_playwright
-
-
-async def test_full_screen(start_fullscreen: bool, maximize: bool):
- async with async_playwright() as p:
- try:
- print('Attempting to connect to Chrome...')
- # run in terminal: /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --no-first-run
- browser = await p.chromium.connect_over_cdp(
- 'http://localhost:9222',
- timeout=20000, # 20 second timeout for connection
- )
- print('Connected to Chrome successfully')
-
- # Get the first context and page, or create new ones if needed
- if len(browser.contexts) == 0:
- context = await browser.new_context(ignore_https_errors=True)
- else:
- context = browser.contexts[0]
-
- if len(context.pages) == 0:
- page = await context.new_page()
- else:
- page = context.pages[0]
-
- print('Attempting to navigate to Gmail...')
- try:
- # First try with a shorter timeout
- await page.goto(
- 'https://mail.google.com',
- wait_until='load', # Changed from domcontentloaded
- timeout=10000,
- )
- except Exception as e:
- print(f'First navigation attempt failed: {e}')
- print('Trying again with different settings...')
- # If that fails, try again with different settings
- await page.goto(
- 'https://mail.google.com',
- wait_until='commit', # Less strict wait condition
- timeout=30000,
- )
-
- # Wait for the page to stabilize
- await asyncio.sleep(2)
-
- print(f'Current page title: {await page.title()}')
-
- # Optional: wait for specific Gmail elements
- try:
- await page.wait_for_selector('div[role="main"]', timeout=5000)
- print('Gmail interface detected')
- except Exception as e:
- print(f'Note: Gmail interface not detected: {e}')
-
- await asyncio.sleep(30)
- except Exception as e:
- print(f'An error occurred: {e}')
- import traceback
-
- traceback.print_exc()
- finally:
- await browser.close()
-
-
-if __name__ == '__main__':
- asyncio.run(test_full_screen(False, False))
diff --git a/tests/test_dropdown.py b/tests/test_dropdown.py
index a6af88a5e..59aa6e2f6 100644
--- a/tests/test_dropdown.py
+++ b/tests/test_dropdown.py
@@ -8,15 +8,14 @@ from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-async def test_dropdown(llm, browser_context):
+async def test_dropdown(llm, browser_session):
"""Test selecting an option from a dropdown menu."""
agent = Agent(
task=(
'go to https://codepen.io/geheimschriftstift/pen/mPLvQz and first get all options for the dropdown and then select the 5th option'
),
llm=llm,
- browser_context=browser_context,
+ browser_session=browser_session,
)
try:
@@ -28,7 +27,8 @@ async def test_dropdown(llm, browser_context):
assert 'Duck' in result, "Expected 5th option 'Duck' to be selected"
# Verify dropdown state
- element = await browser_context.get_element_by_selector('select')
+ page = await browser_session.get_current_page()
+ element = await page.query_selector('select')
assert element is not None, 'Dropdown element should exist'
value = await element.evaluate('el => el.value')
@@ -36,5 +36,3 @@ async def test_dropdown(llm, browser_context):
except Exception as e:
pytest.fail(f'Dropdown test failed: {str(e)}')
- finally:
- await browser_context.close()
diff --git a/tests/test_dropdown_complex.py b/tests/test_dropdown_complex.py
index ffa2efdab..5b760bed1 100644
--- a/tests/test_dropdown_complex.py
+++ b/tests/test_dropdown_complex.py
@@ -8,15 +8,14 @@ from browser_use.agent.service import Agent
from browser_use.agent.views import AgentHistoryList
-async def test_dropdown_complex(llm, browser_context):
+async def test_dropdown_complex(llm, browser_session):
"""Test selecting an option from a complex dropdown menu."""
agent = Agent(
task=(
'go to https://codepen.io/shyam-king/pen/pvzpByJ and first get all options for the dropdown and then select the json option'
),
llm=llm,
- browser_context=browser_context,
+ browser_session=browser_session,
)
try:
@@ -28,17 +27,16 @@ async def test_dropdown_complex(llm, browser_context):
assert 'json' in result.lower(), "Expected 'json' option to be selected"
# Verify dropdown state
- element = await browser_context.get_element_by_selector('.select-selected')
+ page = await browser_session.get_current_page()
+ element = await page.query_selector('.select-selected')
assert element is not None, 'Custom dropdown element should exist'
text = await element.text_content()
assert 'json' in text.lower(), 'Dropdown should display json option'
# Verify the selected option's effect
- code_element = await browser_context.get_element_by_selector('pre code')
+ code_element = await page.query_selector('pre code')
assert code_element is not None, 'Code element should be visible when JSON is selected'
except Exception as e:
pytest.fail(f'Complex dropdown test failed: {str(e)}')
- finally:
- await browser_context.close()
diff --git a/tests/test_vision.py b/tests/test_vision.py
index a3049e010..7886377bc 100644
--- a/tests/test_vision.py
+++ b/tests/test_vision.py
@@ -40,14 +40,16 @@ async def done(text: str) -> str:
@pytest.mark.skip(reason='this is for local testing only')
async def test_vision():
- agent = Agent(
- task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to explain it and get the next question',
- llm=llm,
- controller=controller,
- browser_session=BrowserSession(headless=False, user_data_dir=None),
- )
+ browser_session = BrowserSession(headless=True, user_data_dir=None)
+ await browser_session.start()
try:
+ agent = Agent(
+ task='call explain_screen all the time the user asks you questions e.g. about the page like bbox which you see are labels - your task is to explain it and get the next question',
+ llm=llm,
+ controller=controller,
+ browser_session=browser_session,
+ )
history: AgentHistoryList = await agent.run(20)
finally:
# Make sure to close the browser
- await agent.browser.close()
+ await browser_session.stop()
diff --git a/tests/test_wait_for_element.py b/tests/test_wait_for_element.py
index 4ffe51cff..b56feec9c 100644
--- a/tests/test_wait_for_element.py
+++ b/tests/test_wait_for_element.py
@@ -14,8 +14,7 @@ from langchain_openai import ChatOpenAI
from browser_use import Agent, Controller
# Local imports
-from browser_use.browser.browser import Browser, BrowserConfig
-from browser_use.browser.context import BrowserContext
+from browser_use.browser import BrowserProfile, BrowserSession
# Load environment variables.
load_dotenv()
@@ -35,33 +34,35 @@ async def test_wait_for_element():
# {'wait_for_element': {'selector': '#search', 'timeout': 30}},
]
- # Set up the browser context.
- context = BrowserContext(
- browser=Browser(config=BrowserConfig(headless=False, disable_security=True)),
- )
-
- # Create the agent with the task.
- agent = Agent(
- task="Wait for element '#search' to be visible with a timeout of 30 seconds.",
- llm=llm,
- browser_context=context,
- initial_actions=initial_actions,
- controller=controller,
- )
-
- # Run the agent for a few steps to trigger navigation and then the wait action.
- history = await agent.run(max_steps=3)
- action_names = history.action_names()
-
- # Ensure that the wait_for_element action was executed.
- assert 'wait_for_element' in action_names, 'Expected wait_for_element action to be executed.'
-
- # Verify that the #search element is visible by querying the page.
- page = await context.get_current_page()
- header_handle = await page.query_selector('#search')
- assert header_handle is not None, 'Expected to find a #search element on the page.'
- is_visible = await header_handle.is_visible()
- assert is_visible, 'Expected the #search element to be visible.'
+ # Set up the browser session.
+ browser_session = BrowserSession(browser_profile=BrowserProfile(headless=True, disable_security=True))
+ await browser_session.start()
+
+ try:
+ # Create the agent with the task.
+ agent = Agent(
+ task="Wait for element '#search' to be visible with a timeout of 30 seconds.",
+ llm=llm,
+ browser_session=browser_session,
+ initial_actions=initial_actions,
+ controller=controller,
+ )
+
+ # Run the agent for a few steps to trigger navigation and then the wait action.
+ history = await agent.run(max_steps=3)
+ action_names = history.action_names()
+
+ # Ensure that the wait_for_element action was executed.
+ assert 'wait_for_element' in action_names, 'Expected wait_for_element action to be executed.'
+
+ # Verify that the #search element is visible by querying the page.
+ page = await browser_session.get_current_page()
+ header_handle = await page.query_selector('#search')
+ assert header_handle is not None, 'Expected to find a #search element on the page.'
+ is_visible = await header_handle.is_visible()
+ assert is_visible, 'Expected the #search element to be visible.'
+ finally:
+ await browser_session.stop()
if __name__ == '__main__':