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
better extraction
Gregor Žuničd756ccb18245
diff --git a/src/browser/service.py b/src/browser/service.pyindex 40df0ccdb..9c2211ee7 100644--- a/src/browser/service.py+++ b/src/browser/service.py@@ -28,8 +28,8 @@ class BrowserService:self.headless = headlessself.driver: webdriver.Chrome | None = Noneself._ob = Screenshot.Screenshot()- self.MINIMUM_WAIT_TIME = 1- self.MAXIMUM_WAIT_TIME = 10+ self.MINIMUM_WAIT_TIME = 0.5+ self.MAXIMUM_WAIT_TIME = 5def init(self) -> webdriver.Chrome:"""@@ -116,7 +116,7 @@ class BrowserService:# Calculate remaining time to meet minimum WAIT_TIMEelapsed = time.time() - start_time- remaining = self.MINIMUM_WAIT_TIME - elapsed+ remaining = max(self.MINIMUM_WAIT_TIME - elapsed, 0)print(f'Page loaded in {elapsed:.2f} seconds, waiting for additional {remaining:.2f} seconds'diff --git a/src/dom/service.py b/src/dom/service.pyindex 9c0667a82..a62ac8a0f 100644--- a/src/dom/service.py+++ b/src/dom/service.py@@ -81,7 +81,7 @@ class DomService:continueif isinstance(element, NavigableString):- text_content = element.strip()+ text_content = self._cap_text_length(element.strip())if text_content:output_string = f'{text_content}'output_items.append(@@ -108,6 +108,12 @@ class DomService:return ProcessedDomContent(items=output_items, selector_map=selector_map)+ def _cap_text_length(self, text: str, max_length: int = 150) -> str:+ if len(text) > max_length:+ half_length = max_length // 2+ return text[:half_length] + '...' + text[-half_length:]+ return text+def _extract_text_from_all_children(self, element: Tag) -> str:# Tell BeautifulSoup that button tags can contain content# if not hasattr(element.parser, 'BUTTON_TAGS'):@@ -121,7 +127,8 @@ class DomService:current_child_text = child.get_text(strip=True)text_content += '\n' + current_child_text- return text_content.strip() or ''++ return self._cap_text_length(text_content.strip()) or ''def _is_interactive_element(self, element: Tag) -> bool:"""Check if element is interactive based on tag name and attributes."""@@ -266,7 +273,7 @@ class DomService:"""essential_attributes = ['id',- # 'class',+ 'class','href','src','readonly',@@ -288,7 +295,13 @@ class DomService:attrs = []for attr in essential_attributes:if attr in element.attrs:- attrs.append(f'{attr}="{element[attr]}"')+ element_attr = element[attr]+ if isinstance(element_attr, str):+ element_attr = element_attr[:50]+ elif isinstance(element_attr, (list, tuple)):+ element_attr = ' '.join(str(v)[:50] for v in element_attr)++ attrs.append(f'{attr}="{element_attr}"')state_attributes_prefixes = ('aria-',diff --git a/src/dom/tests/extraction_test.py b/src/dom/tests/extraction_test.pyindex 21d1cf682..2d2888fc6 100644--- a/src/dom/tests/extraction_test.py+++ b/src/dom/tests/extraction_test.py@@ -34,7 +34,13 @@ def test_process_html_file():# )# )- print(dom_service.get_clickable_elements().dom_items_to_string())+ start_time = time.time()+ elements = dom_service.get_clickable_elements().dom_items_to_string()+ elapsed_time = time.time() - start_time++ print(f'get_clickable_elements took {elapsed_time:.2f} seconds')++ print(elements)# for item in result.items:# print(item)diff --git a/src/tests/test_kayak_search.py b/src/tests/test_kayak_search.pyindex 8f5d9a3c9..c5fcd7b79 100644--- a/src/tests/test_kayak_search.py+++ b/src/tests/test_kayak_search.py@@ -1,8 +1,8 @@import datetimeimport os-import timeimport pytest+from langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAIfrom src.agent.service import AgentService@@ -31,7 +31,10 @@ async def test_kayak_flight_search():run_folder = setup_run_folder('kayak_com_flight_search2')controller = ControllerService()- model = ChatOpenAI(model='gpt-4o')++ # model = ChatOpenAI(model='gpt-4o')+ model = ChatAnthropic(model_name='claude-3-5-sonnet-20240620', timeout=25, stop=None)+agent = AgentService(task, model, controller, use_vision=True)print('\n' + '=' * 50)@@ -47,8 +50,6 @@ async def test_kayak_flight_search():print('action:\n', action)print('result:\n', result)- time.sleep(0.5)-# current_state = agent.get_current_state()# save_formatted_html(# current_state.interactable_elements, f'{run_folder}/current_state_{i}.html'