Skip to content

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

option to disable chrome security, cross site iframes work

Gregor Žuničd64448923f78
diff --git a/browser_use/browser/service.py b/browser_use/browser/service.py
index 5ad929abc..a755ae4ae 100644
--- a/browser_use/browser/service.py
+++ b/browser_use/browser/service.py
@@ -9,7 +9,14 @@ import time
from dataclasses import dataclass
from playwright.async_api import Browser as PlaywrightBrowser
-from playwright.async_api import BrowserContext, ElementHandle, Page, Playwright, async_playwright
+from playwright.async_api import (
+ BrowserContext,
+ ElementHandle,
+ FrameLocator,
+ Page,
+ Playwright,
+ async_playwright,
+)
from browser_use.browser.views import BrowserError, BrowserState, TabInfo
from browser_use.dom.service import DomService
@@ -34,9 +41,12 @@ class Browser:
MINIMUM_WAIT_TIME = 0.5
MAXIMUM_WAIT_TIME = 5
- def __init__(self, headless: bool = False, keep_open: bool = False):
+ def __init__(
+ self, headless: bool = False, keep_open: bool = False, disable_security: bool = False
+ ):
self.headless = headless
self.keep_open = keep_open
+ self.disable_security = disable_security
# Initialize these as None - they'll be set up when needed
self.session: BrowserSession | None = None
@@ -68,8 +78,19 @@ class Browser:
cached_state=initial_state,
)
+ await self._add_new_page_listener(context)
+
return self.session
+ async def _add_new_page_listener(self, context: BrowserContext):
+ async def on_page(page: Page):
+ await page.wait_for_load_state()
+ logger.debug(f'New page opened: {page.url}')
+ if self.session is not None:
+ self.session.current_page = page
+
+ context.on('page', on_page)
+
async def get_session(self) -> BrowserSession:
"""Lazy initialization of the browser and related components"""
if self.session is None:
@@ -84,6 +105,13 @@ class Browser:
async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
"""Sets up and returns a Playwright Browser instance with anti-detection measures."""
try:
+ disable_security_args = []
+ if self.disable_security:
+ disable_security_args = [
+ '--disable-web-security',
+ '--disable-site-isolation-trials',
+ '--disable-features=IsolateOrigins,site-per-process',
+ ]
browser = await playwright.chromium.launch(
headless=self.headless,
ignore_default_args=['--enable-automation'], # Helps with anti-detection
@@ -102,7 +130,8 @@ class Browser:
'--no-default-browser-check',
'--no-startup-window', # Prevents initial focus
'--window-position=0,0',
- ],
+ ]
+ + disable_security_args,
)
return browser
@@ -119,6 +148,8 @@ class Browser:
'(KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
),
java_script_enabled=True,
+ bypass_csp=self.disable_security,
+ ignore_https_errors=self.disable_security,
)
# Expose anti-detection scripts
@@ -154,7 +185,7 @@ class Browser:
return context
- async def wait_for_page_load(self, timeout_overwrite: float | None = None):
+ async def _wait_for_page_and_frames_load(self, timeout_overwrite: float | None = None):
"""
Ensures page is fully loaded before continuing.
Waits for either document.readyState to be complete or minimum WAIT_TIME, whichever is longer.
@@ -166,10 +197,28 @@ class Browser:
# Wait for page load
try:
- await page.wait_for_load_state('load', timeout=5000)
+ await page.wait_for_load_state('domcontentloaded', timeout=5000)
except Exception:
+ logger.warning('Page load failed, continuing...')
pass
+ # Wait for all frames to load
+ async def wait_for_frame_and_subframes(frame):
+ try:
+ await frame.wait_for_load_state('domcontentloaded', timeout=5_000)
+ except Exception:
+ logger.warning('Frame load failed, continuing...')
+ pass
+
+ # Recursively wait for all child frames
+ for child_frame in frame.child_frames:
+ await wait_for_frame_and_subframes(child_frame)
+
+ # Wait for main page frames and their subframes
+ frames = page.frames
+ for frame in frames:
+ await wait_for_frame_and_subframes(frame)
+
# Calculate remaining time to meet minimum WAIT_TIME
elapsed = time.time() - start_time
remaining = max((timeout_overwrite or self.MINIMUM_WAIT_TIME) - elapsed, 0)
@@ -203,25 +252,25 @@ class Browser:
"""Navigate to a URL"""
page = await self.get_current_page()
await page.goto(url)
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
async def refresh_page(self):
"""Refresh the current page"""
page = await self.get_current_page()
await page.reload()
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
async def go_back(self):
"""Navigate back in history"""
page = await self.get_current_page()
await page.go_back()
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
async def go_forward(self):
"""Navigate forward in history"""
page = await self.get_current_page()
await page.go_forward()
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
async def close_current_tab(self):
"""Close the current tab"""
@@ -248,12 +297,14 @@ class Browser:
@time_execution_sync('--get_state') # This decorator might need to be updated to handle async
async def get_state(self, use_vision: bool = False) -> BrowserState:
"""Get the current state of the browser"""
+ await self._wait_for_page_and_frames_load()
session = await self.get_session()
session.cached_state = await self._update_state(use_vision=use_vision)
return session.cached_state
async def _update_state(self, use_vision: bool = False) -> BrowserState:
"""Update and return state."""
+ await self.remove_highlights()
page = await self.get_current_page()
dom_service = DomService(page)
content = await dom_service.get_clickable_elements() # Assuming this is async
@@ -316,25 +367,91 @@ class Browser:
# endregion
# region - User Actions
+ def _convert_simple_xpath_to_css_selector(self, xpath: str) -> str:
+ """Converts simple XPath expressions to CSS selectors.
+ Only handles basic XPath patterns like tag names, indices, and attributes.
+ """
+ # Remove leading slash if present
+ xpath = xpath.lstrip('/')
+
+ # Split into parts
+ parts = xpath.split('/')
+
+ css_parts = []
+ for part in parts:
+ if not part:
+ continue
+
+ # Handle index notation [n]
+ if '[' in part:
+ tag = part[: part.find('[')]
+ index = int(part[part.find('[') + 1 : part.find(']')]) - 1
+ css_parts.append(f'{tag}:nth-of-type({index+1})')
+ else:
+ css_parts.append(part)
+
+ return ' > '.join(css_parts)
+
+ def _enhanced_css_selector_for_element(self, element: DOMElementNode) -> str:
+ css_selector = self._convert_simple_xpath_to_css_selector(element.xpath)
+
+ # Handle class attributes first
+ if 'class' in element.attributes:
+ classes = element.attributes['class'].split()
+ css_selector += '.' + '.'.join(classes)
+
+ # Then add all other attribute selectors
+ for attribute, value in element.attributes.items():
+ if attribute != 'class': # Skip class since we already handled it
+ css_selector += f'[{attribute}="{value}"]'
+
+ return css_selector
+
async def get_locate_element(self, element: DOMElementNode):
- page = await self.get_current_page()
- return await page.wait_for_selector(f'xpath={element.xpath}', timeout=5000, state='visible')
+ current_frame = await self.get_current_page()
+
+ # Start with the target element and collect all parents
+ parents: list[DOMElementNode] = []
+ current = element
+ while current.parent is not None:
+ parent = current.parent
+ parents.append(parent)
+ current = parent
+ if parent.tag_name == 'iframe':
+ break
+
+ # there can be only one iframe parent (by design of the loop above)
+ iframe_parent = [item for item in parents if item.tag_name == 'iframe']
+ if iframe_parent:
+ parent = iframe_parent[0]
+ css_selector = self._enhanced_css_selector_for_element(parent)
+ current_frame = current_frame.frame_locator(css_selector)
+
+ css_selector = self._enhanced_css_selector_for_element(element)
+
+ if isinstance(current_frame, FrameLocator):
+ return await current_frame.locator(css_selector).element_handle()
+ else:
+ return await current_frame.wait_for_selector(
+ css_selector, timeout=5000, state='visible'
+ )
async def _input_text_element_node(self, element_node: DOMElementNode, text: str):
try:
+ page = await self.get_current_page()
element = await self.get_locate_element(element_node)
if element is None:
- raise Exception(f'Element with xpath: {element_node.xpath} not found')
+ raise Exception(f'Element: {repr(element_node)} not found')
await element.scroll_into_view_if_needed(timeout=2500)
await element.fill('')
await element.type(text)
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
except Exception as e:
raise Exception(
- f'Failed to input text into element with xpath: {element_node.xpath}. Error: {str(e)}'
+ f'Failed to input text into element: {repr(element_node)}. Error: {str(e)}'
)
async def _click_element_node(self, element_node: DOMElementNode):
@@ -347,28 +464,22 @@ class Browser:
element = await self.get_locate_element(element_node)
if element is None:
- raise Exception(f'Element with xpath: {element_node.xpath} not found')
+ raise Exception(f'Element: {repr(element_node)} not found')
# await element.scroll_into_view_if_needed()
try:
await element.click(timeout=2500)
- await self.wait_for_page_load()
- return
+ await page.wait_for_load_state()
except Exception:
- pass
-
- try:
- await page.evaluate('(el) => el.click()', element)
- await self.wait_for_page_load()
- return
- except Exception as e:
- raise Exception(f'Failed to click element: {str(e)}')
+ try:
+ await page.evaluate('(el) => el.click()', element)
+ await page.wait_for_load_state()
+ except Exception as e:
+ raise Exception(f'Failed to click element: {str(e)}')
except Exception as e:
- raise Exception(
- f'Failed to click element with xpath: {element_node.xpath}. Error: {str(e)}'
- )
+ raise Exception(f'Failed to click element: {repr(element_node)}. Error: {str(e)}')
async def get_tabs_info(self) -> list[TabInfo]:
"""Get information about all tabs"""
@@ -396,7 +507,7 @@ class Browser:
session.current_page = page
await page.bring_to_front()
- await self.wait_for_page_load()
+ await page.wait_for_load_state()
async def create_new_tab(self, url: str | None = None) -> None:
"""Create a new tab and optionally navigate to a URL"""
@@ -404,13 +515,13 @@ class Browser:
new_page = await session.context.new_page()
session.current_page = new_page
- await self.wait_for_page_load()
+ await new_page.wait_for_load_state()
page = await self.get_current_page()
if url:
await page.goto(url)
- await self.wait_for_page_load(timeout_overwrite=1)
+ await self._wait_for_page_and_frames_load(timeout_overwrite=1)
# endregion
@@ -419,14 +530,8 @@ class Browser:
session = await self.get_session()
return session.cached_state.selector_map
- async def get_xpath(self, index: int) -> str:
- selector_map = await self.get_selector_map()
- return selector_map[index].xpath
-
async def get_element_by_index(self, index: int) -> ElementHandle | None:
- page = await self.get_current_page()
- return await page.wait_for_selector(
- await self.get_xpath(index), timeout=2500, state='visible'
- )
+ selector_map = await self.get_selector_map()
+ return await self.get_locate_element(selector_map[index])
# endregion
diff --git a/browser_use/browser/tests/test_clicks.py b/browser_use/browser/tests/test_clicks.py
index cf441bfdc..3c66205d9 100644
--- a/browser_use/browser/tests/test_clicks.py
+++ b/browser_use/browser/tests/test_clicks.py
@@ -1,14 +1,16 @@
-import time
+import asyncio
+import json
import pytest
from browser_use.browser.service import Browser
+from browser_use.dom.views import ElementTreeSerializer
from browser_use.utils import time_execution_sync
@pytest.mark.asyncio
async def test_highlight_elements():
- browser = Browser(headless=False, keep_open=False)
+ browser = Browser(headless=False, keep_open=False, disable_security=True)
session = await browser.get_session()
@@ -16,46 +18,55 @@ async def test_highlight_elements():
page = await browser.get_current_page()
# await page.goto('https://immobilienscout24.de')
- await page.goto('https://kayak.com')
+ await page.goto('https://help.sap.com/docs/sap-ai-core/sap-ai-core-service-guide/service-plans')
+ # await page.goto('https://kayak.com')
+ # await page.goto('https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe')
- time.sleep(1.5)
- # 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']]")
+ await asyncio.sleep(1)
while True:
- state = await browser.get_state()
+ try:
+ # await asyncio.sleep(10)
+ state = await browser.get_state()
- # await time_execution_sync('highlight_selector_map_elements')(
- # browser.highlight_selector_map_elements
- # )(state.selector_map)
+ with open('./tmp/page.json', 'w') as f:
+ json.dump(
+ ElementTreeSerializer.dom_element_node_to_json(state.element_tree), f, indent=1
+ )
- # print(state.dom_items_to_string(use_tabs=False))
- # print(state.selector_map)
+ # await time_execution_sync('highlight_selector_map_elements')(
+ # browser.highlight_selector_map_elements
+ # )(state.selector_map)
- # Find and print duplicate XPaths
- xpath_counts = {}
- for selector in state.selector_map.values():
- xpath = selector.xpath
- if xpath in xpath_counts:
- xpath_counts[xpath] += 1
- else:
- xpath_counts[xpath] = 1
+ # print(state.dom_items_to_string(use_tabs=False))
+ # print(state.selector_map)
- print('\nDuplicate XPaths found:')
- for xpath, count in xpath_counts.items():
- if count > 1:
- print(f'XPath: {xpath}')
- print(f'Count: {count}\n')
+ # Find and print duplicate XPaths
+ xpath_counts = {}
+ for selector in state.selector_map.values():
+ xpath = selector.xpath
+ if xpath in xpath_counts:
+ xpath_counts[xpath] += 1
+ else:
+ xpath_counts[xpath] = 1
- print(state.selector_map.keys(), 'Selector map keys')
- action = input('Select next action: ')
+ print('\nDuplicate XPaths found:')
+ for xpath, count in xpath_counts.items():
+ if count > 1:
+ print(f'XPath: {xpath}')
+ print(f'Count: {count}\n')
- await time_execution_sync('remove_highlight_elements')(browser.remove_highlights)()
+ print(state.selector_map.keys(), 'Selector map keys')
+ print(state.element_tree.clickable_elements_to_string(use_tabs=False))
+ action = input('Select next action: ')
- xpath = state.selector_map[int(action)]
+ await time_execution_sync('remove_highlight_elements')(browser.remove_highlights)()
- # check if index of selector map are the same as index of items in dom_items
+ node_element = state.selector_map[int(action)]
- await browser._click_element_node(xpath)
+ # check if index of selector map are the same as index of items in dom_items
+
+ await browser._click_element_node(node_element)
+
+ except Exception as e:
+ print(e)
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index 56a818cc6..f3475af3b 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -37,19 +37,19 @@ class Controller:
async def search_google(params: SearchGoogleAction, browser: Browser):
page = await browser.get_current_page()
await page.goto(f'https://www.google.com/search?q={params.query}')
- await browser.wait_for_page_load()
+ await page.wait_for_load_state()
@self.registry.action('Navigate to URL', param_model=GoToUrlAction, requires_browser=True)
async def go_to_url(params: GoToUrlAction, browser: Browser):
page = await browser.get_current_page()
await page.goto(params.url)
- await browser.wait_for_page_load()
+ await page.wait_for_load_state()
@self.registry.action('Go back', requires_browser=True)
async def go_back(browser: Browser):
page = await browser.get_current_page()
await page.go_back()
- await browser.wait_for_page_load()
+ await page.wait_for_load_state()
# Element Interaction Actions
@self.registry.action(
@@ -105,7 +105,8 @@ class Controller:
async def switch_tab(params: SwitchTabAction, browser: Browser):
await browser.switch_to_tab(params.page_id)
# Wait for tab to be ready
- await browser.wait_for_page_load()
+ page = await browser.get_current_page()
+ await page.wait_for_load_state()
@self.registry.action('Open new tab', param_model=OpenTabAction, requires_browser=True)
async def open_tab(params: OpenTabAction, browser: Browser):
diff --git a/browser_use/dom/buildDomTree.js b/browser_use/dom/buildDomTree.js
index a60da331c..bdde6218c 100644
--- a/browser_use/dom/buildDomTree.js
+++ b/browser_use/dom/buildDomTree.js
@@ -270,7 +270,7 @@ function isTextNodeVisible(textNode) {
rect.height !== 0 &&
rect.top >= 0 &&
rect.top <= window.innerHeight &&
- textNode.parentElement.checkVisibility({
+ textNode.parentElement?.checkVisibility({
checkOpacity: true,
checkVisibilityCSS: true
});
@@ -311,8 +311,10 @@ function buildDomTree(node, parentIframe = null) {
// Copy all attributes if the node is an element
if (node.nodeType === Node.ELEMENT_NODE && node.attributes) {
- for (const attr of node.attributes) {
- nodeData.attributes[attr.name] = attr.value;
+ // Use getAttributeNames() instead of directly iterating attributes
+ const attributeNames = node.getAttributeNames?.() || [];
+ for (const name of attributeNames) {
+ nodeData.attributes[name] = node.getAttribute(name);
}
}
@@ -333,9 +335,9 @@ function buildDomTree(node, parentIframe = null) {
}
// Only add iframeContext if we're inside an iframe
- if (parentIframe) {
- nodeData.iframeContext = `iframe[src="${parentIframe.src || ''}"]`;
- }
+ // if (parentIframe) {
+ // nodeData.iframeContext = `iframe[src="${parentIframe.src || ''}"]`;
+ // }
// Only add shadowRoot field if it exists
if (node.shadowRoot) {
diff --git a/browser_use/dom/service.py b/browser_use/dom/service.py
index 6cf6946d6..0a8b463c6 100644
--- a/browser_use/dom/service.py
+++ b/browser_use/dom/service.py
@@ -52,7 +52,9 @@ class DomService:
return selector_map
def _parse_node(
- self, node_data: dict, parent: Optional[DOMElementNode] = None
+ self,
+ node_data: dict,
+ parent: Optional[DOMElementNode] = None,
) -> Optional[DOMBaseNode]:
if not node_data:
return None
@@ -66,16 +68,17 @@ class DomService:
return text_node
+ tag_name = node_data['tagName']
+
element_node = DOMElementNode(
- tag_name=node_data['tagName'],
+ tag_name=tag_name,
xpath=node_data['xpath'],
attributes=node_data.get('attributes', {}),
children=[], # Initialize empty, will fill later
- is_visible=node_data['isVisible'],
- is_interactive=node_data['isInteractive'],
- is_top_element=node_data['isTopElement'],
+ is_visible=node_data.get('isVisible', False),
+ is_interactive=node_data.get('isInteractive', False),
+ is_top_element=node_data.get('isTopElement', False),
highlight_index=node_data.get('highlightIndex'),
- iframe_context=node_data.get('iframeContext'),
shadow_root=node_data.get('shadowRoot', False),
parent=parent,
)
diff --git a/browser_use/dom/views.py b/browser_use/dom/views.py
index 32c05bcea..53895b79a 100644
--- a/browser_use/dom/views.py
+++ b/browser_use/dom/views.py
@@ -29,16 +29,44 @@ class DOMTextNode(DOMBaseNode):
@dataclass(frozen=False)
class DOMElementNode(DOMBaseNode):
+ """
+ xpath: the xpath of the element from the last root node (shadow root or iframe OR document if no shadow root or iframe).
+ To properly reference the element we need to recursively switch the root node until we find the element (work you way up the tree with `.parent`)
+ """
+
tag_name: str
xpath: str
attributes: Dict[str, str]
children: List[DOMBaseNode]
is_interactive: bool = False
is_top_element: bool = False
- iframe_context: Optional[str] = None
shadow_root: bool = False
highlight_index: Optional[int] = None
+ def __repr__(self) -> str:
+ tag_str = f'<{self.tag_name}'
+
+ # Add attributes
+ for key, value in self.attributes.items():
+ tag_str += f' {key}="{value}"'
+ tag_str += '>'
+
+ # Add extra info
+ extras = []
+ if self.is_interactive:
+ extras.append('interactive')
+ if self.is_top_element:
+ extras.append('top')
+ if self.shadow_root:
+ extras.append('shadow-root')
+ if self.highlight_index is not None:
+ extras.append(f'highlight:{self.highlight_index}')
+
+ if extras:
+ tag_str += f' [{", ".join(extras)}]'
+
+ return tag_str
+
def get_all_text_till_next_clickable_element(self) -> str:
text_parts = []
@@ -92,30 +120,22 @@ class ElementTreeSerializer:
def serialize_clickable_elements(element_tree: DOMElementNode) -> str:
return element_tree.clickable_elements_to_string()
- # def reconstruct_html_from_clickable_elements(self, element_tree: ElementNode) -> str:
- # """Convert the clickable elements back into HTML format."""
- # html_parts = []
-
- # def process_node(node: BaseNode) -> None:
- # if isinstance(node, ElementNode):
- # # Start tag
- # attributes = ' '.join(f'{k}="{v}"' for k, v in node.attributes.items())
- # tag_start = f'<{node.tag_name}'
- # if attributes:
- # tag_start += f' {attributes}'
- # html_parts.append(f'{tag_start}>')
-
- # # Process children
- # for child in node.children:
- # process_node(child)
-
- # # End tag
- # html_parts.append(f'</{node.tag_name}>')
- # elif isinstance(node, TextNode) and node.is_visible:
- # html_parts.append(node.text)
-
- # process_node(element_tree)
- # return ''.join(html_parts)
+ @staticmethod
+ def dom_element_node_to_json(element_tree: DOMElementNode) -> dict:
+ def node_to_dict(node: DOMBaseNode) -> dict:
+ if isinstance(node, DOMTextNode):
+ return {'type': 'text', 'text': node.text}
+ elif isinstance(node, DOMElementNode):
+ return {
+ 'type': 'element',
+ 'tag_name': node.tag_name,
+ 'attributes': node.attributes,
+ 'highlight_index': node.highlight_index,
+ 'children': [node_to_dict(child) for child in node.children],
+ }
+ return {}
+
+ return node_to_dict(element_tree)
SelectorMap = dict[int, DOMElementNode]