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
Add viewport_expansion to config
magmuellerbcf0b67cf57e
diff --git a/browser_use/browser/context.py b/browser_use/browser/context.pyindex 059d1360e..529d98f42 100644--- a/browser_use/browser/context.py+++ b/browser_use/browser/context.py@@ -83,6 +83,12 @@ class BrowserContextConfig:user_agent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'custom user agent to use.++ highlight_elements: True+ Highlight elements in the DOM on the screen++ viewport_expansion: 800+ Viewport expansion in pixels. This amount will increase the number of elements which are included in the state what the LLM will see. If set to -1, all elements will be included (this leads to high token usage). If set to 0, only the elements which are visible in the viewport will be included."""cookies_file: str | None = None@@ -103,6 +109,9 @@ class BrowserContextConfig:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36')+ highlight_elements: bool = True+ viewport_expansion: int = 800+@dataclassclass BrowserSession:@@ -283,6 +292,12 @@ class BrowserContext:Promise.resolve({ state: Notification.permission }) :originalQuery(parameters));+ (function () {+ const originalAttachShadow = Element.prototype.attachShadow;+ Element.prototype.attachShadow = function attachShadow(options) {+ return originalAttachShadow.call(this, { ...options, mode: "open" });+ };+ })();""")@@ -566,7 +581,11 @@ class BrowserContext:try:await self.remove_highlights()dom_service = DomService(page)- content = await dom_service.get_clickable_elements(focus_element=focus_element)+ content = await dom_service.get_clickable_elements(+ focus_element=focus_element,+ viewport_expansion=self.config.viewport_expansion,+ highlight_elements=self.config.highlight_elements,+ )screenshot_b64 = Noneif use_vision:diff --git a/browser_use/dom/tests/extraction_test.py b/browser_use/dom/tests/extraction_test.pyindex 02edb08c1..6ec4c001c 100644--- a/browser_use/dom/tests/extraction_test.py+++ b/browser_use/dom/tests/extraction_test.py@@ -1,43 +1,116 @@+import asyncioimport timefrom tokencost import count_string_tokensfrom browser_use.browser.browser import Browser, BrowserConfig--# from browser_use.browser.service import Browserfrom browser_use.dom.service import DomServicefrom browser_use.utils import time_execution_sync-# @pytest.mark.skip("slow af")async def test_process_html_file():browser = Browser(config=BrowserConfig(headless=False))+ websites = [+ 'https://kayak.com/flights',+ 'https://immobilienscout24.de',+ 'https://google.com',+ 'https://amazon.com',+ 'https://github.com',+ ]+async with await browser.new_context() as context:page = await context.get_current_page()+ dom_service = DomService(page)++ for website in websites:+ print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')+ await page.goto(website)+ time.sleep(2) # Additional wait for dynamic content++ async def test_viewport(expansion: int, description: str):+ print(f'\n{description}:')+ dom_state = await time_execution_sync(f'get_clickable_elements ({description})')(+ dom_service.get_clickable_elements+ )(highlight_elements=True, viewport_expansion=expansion)++ elements = dom_state.element_tree+ selector_map = dom_state.selector_map+ element_count = len(selector_map.keys())+ token_count = count_string_tokens(elements.clickable_elements_to_string(), model='gpt-4o')++ print(f'Number of elements: {element_count}')+ print(f'Token count: {token_count}')+ return element_count, token_count++ expansions = [0, 100, 200, 300, 400, 500, 600, 1000, -1, -200]+ results = []++ for i, expansion in enumerate(expansions):+ description = (+ f'{i + 1}. Expansion {expansion}px' if expansion >= 0 else f'{i + 1}. All elements ({expansion} expansion)'+ )+ count, tokens = await test_viewport(expansion, description)+ results.append((count, tokens))+ input('Press Enter to continue...')+ await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')++ # Print comparison summary+ print('\nComparison Summary:')+ for i, (count, tokens) in enumerate(results):+ expansion = expansions[i]+ description = f'Expansion {expansion}px' if expansion >= 0 else 'All elements (-1)'+ initial_count, initial_tokens = results[0]+ print(f'{description}: {count} elements (+{count - initial_count}), {tokens} tokens')++ input('\nPress Enter to continue to next website...')++ # Clear highlights before next website+ await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')++async def test_focus_vs_all_elements():+ browser = Browser(config=BrowserConfig(headless=False))++ websites = [+ 'https://google.com', # Simple UI+ 'https://amazon.com', # Complex UI+ ]++ async with await browser.new_context() as context:+ page = await context.get_current_page()dom_service = DomService(page)- # await page.goto('https://kayak.com/flights')- # browser.go_to_url('https://google.com/flights')- await page.goto('https://immobilienscout24.de')-- time.sleep(3)- # browser._click_element_by_xpath(- # '/html/body/div[5]/div/div[2]/div/div/div[3]/div/div[1]/button[1]'- # )- # browser._click_element_by_xpath("//button[div/div[text()='Alle akzeptieren']]")-- dom_state = await time_execution_sync('get_clickable_elements')(- dom_service.get_clickable_elements- )()- elements = dom_state.element_tree- selector_map = dom_state.selector_map-- print(elements.clickable_elements_to_string())- print(- 'Tokens:', count_string_tokens(elements.clickable_elements_to_string(), model='gpt-4o')- )- print(len(selector_map.keys()), 'elements highlighted')-- input('Press Enter to continue...')+ for website in websites:+ print(f'\n{"=" * 50}\nTesting {website}\n{"=" * 50}')+ await page.goto(website)+ time.sleep(2) # Additional wait for dynamic content++ # First get all elements+ print('\nGetting all elements:')+ all_elements_state = await time_execution_sync('get_all_elements')(dom_service.get_clickable_elements)(+ highlight_elements=True, viewport_expansion=0+ )++ selector_map = all_elements_state.selector_map+ total_elements = len(selector_map.keys())+ print(f'Total number of elements: {total_elements}')++ answer = input('Which element do you want to focus on? (Enter index): ')+ await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')++ focus_element = int(answer)+ focus_state = await time_execution_sync('get_focused_element')(dom_service.get_clickable_elements)(+ highlight_elements=True, focus_element=focus_element, viewport_expansion=0+ )+ focus_selector_map = focus_state.selector_map+ focus_element_count = len(focus_selector_map.keys())+ print(f'Number of highlighted elements when focused: {focus_element_count}')++ input('Press Enter to clear highlights and continue...')+ await page.evaluate('document.getElementById("playwright-highlight-container")?.remove()')+++if __name__ == '__main__':+ asyncio.run(test_focus_vs_all_elements())+ asyncio.run(test_process_html_file())