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
processing 2.0
Gregor Žunič219e8ee08583
diff --git a/.gitignore b/.gitignoreindex a2e44a0b0..d4de66df5 100644--- a/.gitignore+++ b/.gitignore@@ -160,4 +160,4 @@ cython_debug/# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/-# temp\ No newline at end of file+temp\ No newline at end of filediff --git a/requirement.txt b/requirement.txtdeleted file mode 100644index e2ebdc30b..000000000--- a/requirement.txt+++ /dev/null@@ -1,452 +0,0 @@-absl-py==2.1.0-affine==2.4.0-aiohttp==3.9.5-aiohttp-cors==0.7.0-aiosignal==1.3.1-altgraph @ file:///AppleInternal/Library/BuildRoots/860631e9-c1c5-11ee-98ee-b6ef2fd8d87b/Library/Caches/com.apple.xbs/Sources/python3/altgraph-0.17.2-py2.py3-none-any.whl-annotated-types==0.6.0-antlr4-python3-runtime==4.9.3-anyio==4.3.0-appdirs==1.4.4-appnope==0.1.4-arabic-reshaper==3.0.0-asttokens==2.2.1-astunparse==1.6.3-async-timeout==4.0.3-attrs==24.2.0-backcall==0.2.0-backports.functools-lru-cache==1.6.4-beautifulsoup4==4.12.3-bitstring==4.0.1-black==24.4.2-bleach==6.1.0-blinker==1.8.2-blosc2==2.5.1-bokeh==2.4.3-Bottleneck==1.3.6-branca==0.6.0-brotlipy==0.7.0-cached-property==1.5.2-cachetools==5.3.3-Cartopy==0.21.1-certifi==2022.12.7-cffi==1.15.1-cfgrib==0.9.9.1-cftime==1.6.2-charset-normalizer==2.1.1-click==8.1.3-click-plugins==1.1.1-cligj==0.7.2-climada==3.3.1-cloudpickle==2.2.1-colorama==0.4.6-colorful==0.5.6-comm==0.1.2-contextily==1.3.0-contourpy==1.2.1-cryptography==39.0.1-cycler==0.11.0-Cython==3.0.10-cytoolz==0.12.0-dask==2023.2.0-debugpy==1.6.6-decorator==5.1.1-defusedxml==0.7.1-deprecation==2.1.0-diffusers==0.30.2-dill==0.3.6-diskcache==5.6.3-distlib==0.3.8-distributed==2023.2.0-distro==1.9.0-docker-pycreds==0.4.0-docopt==0.6.2-dukpy==0.3.1-easydict==1.13-eccodes==1.5.1-einops==0.7.0-elementpath==4.4.0-esprima==4.0.1-et-xmlfile==1.1.0-exceptiongroup==1.2.0-executing==1.2.0-Farama-Notifications==0.0.4-fastapi==0.110.3-fastjsonschema==2.19.1-ffpyplayer==4.5.1-filelock==3.13.1-findlibs==0.0.2-Fiona==1.8.21-Flask==3.0.3-folium==0.14.0-fonttools==4.51.0-freetype-py==2.4.0-frozenlist==1.4.1-fsspec==2024.9.0-future @ file:///AppleInternal/Library/BuildRoots/860631e9-c1c5-11ee-98ee-b6ef2fd8d87b/Library/Caches/com.apple.xbs/Sources/python3/future-0.18.2-py3-none-any.whl-geographiclib==1.52-geopandas==0.12.2-geopy==2.3.0-gevent==24.2.1-gguf==0.6.0-gitdb==4.0.11-GitPython==3.1.43-google-api-core==2.18.0-google-auth==2.29.0-googleapis-common-protos==1.63.0-greenlet==3.0.3-grpcio==1.62.1-gym==0.26.2-gym-notices==0.0.8-gymnasium==0.29.1-h11==0.14.0-h5py==3.7.0-haversine==2.7.0-HeapDict==1.0.1-html2text==2024.2.26-httpcore==1.0.5-httptools==0.6.1-httpx==0.27.0-huggingface-hub==0.24.6-idna==3.4-imageio==2.34.1-imageio-ffmpeg==0.4.9-importlib-metadata==6.0.0-importlib_resources==6.4.0-ipykernel==6.21.2-ipython==8.10.0-itsdangerous==2.2.0-javascripthon==0.12-jedi==0.18.2-Jinja2==3.1.2-joblib==1.2.0-json-tricks==3.17.3-jsonschema==4.21.1-jsonschema-specifications==2023.12.1-jupyter_client==8.0.3-jupyter_core==5.2.0-jupyterlab_pygments==0.3.0-kiwisolver==1.4.4-linkify-it-py==2.0.3-llama_cpp_python==0.2.56-llmsherpa==0.1.4-llvmlite==0.39.1-lmdb==1.5.1-locket==1.0.0-lvis==0.5.3-lxml==4.9.2-lz4==4.3.2-macholib @ file:///AppleInternal/Library/BuildRoots/860631e9-c1c5-11ee-98ee-b6ef2fd8d87b/Library/Caches/com.apple.xbs/Sources/python3/macholib-1.15.2-py2.py3-none-any.whl-mapclassify==2.5.0-Markdown==3.6-markdown-it-py==3.0.0-MarkupSafe==2.1.2-matplotlib==3.9.2-matplotlib-inline==0.1.6-mdit-py-plugins==0.4.0-mdurl==0.1.2-memray==1.12.0-mercantile==1.2.1-mistune==3.0.2-mpmath==1.3.0-msgpack==1.0.4-msgpack-numpy==0.4.8-multidict==6.0.5-multiprocess==0.70.14-munch==2.5.0-mypy-extensions==1.0.0-nbclient==0.10.0-nbconvert==7.16.3-nbformat==5.10.4-ndindex==1.8-nest-asyncio==1.5.6-netCDF4==1.6.0-networkx==3.0-numba==0.56.4-numexpr==2.8.3-numpy==1.23.5-omegaconf==2.3.0-openai==1.25.1-opencensus==0.11.4-opencensus-context==0.1.3-opencv-python==4.9.0.80-openpyxl==3.1.1-outcome==1.3.0.post0-overpy==0.6-packaging==23.0-pandas==1.5.3-pandas-datareader==0.10.0-pandocfilters==1.5.1-parso==0.8.3-partd==1.3.0-pathos==0.3.0-pathspec==0.12.1-patsy==0.5.3-peewee==3.15.4-pexpect==4.8.0-pickleshare==0.7.5-Pillow==9.2.0-Pint==0.20.1-pipreqs==0.5.0-platformdirs==3.0.0-pooch==1.6.0-pox==0.3.2-ppft==1.7.6.6-prometheus_client==0.20.0-prompt-toolkit==3.0.36-proto-plus==1.23.0-protobuf==4.25.3-psutil==5.9.4-psychtoolbox==3.0.19.0-ptyprocess==0.7.0-pure-eval==0.2.2-py-cpuinfo==9.0.0-py-spy==0.3.14-pyasn1==0.6.0-pyasn1_modules==0.4.0-pybufrkit==0.2.20-pycountry==22.3.5-pycparser==2.21-pydantic==2.7.1-pydantic_core==2.18.2-pydub==0.25.1-pyepsg==0.4.0-pyglet==1.5.27-Pygments==2.14.0-pyobjc==7.3-pyobjc-core==7.3-pyobjc-framework-Accessibility==7.3-pyobjc-framework-Accounts==7.3-pyobjc-framework-AddressBook==7.3-pyobjc-framework-AdServices==7.3-pyobjc-framework-AdSupport==7.3-pyobjc-framework-AppleScriptKit==7.3-pyobjc-framework-AppleScriptObjC==7.3-pyobjc-framework-ApplicationServices==7.3-pyobjc-framework-AppTrackingTransparency==7.3-pyobjc-framework-AuthenticationServices==7.3-pyobjc-framework-AutomaticAssessmentConfiguration==7.3-pyobjc-framework-Automator==7.3-pyobjc-framework-AVFoundation==7.3-pyobjc-framework-AVKit==7.3-pyobjc-framework-BusinessChat==7.3-pyobjc-framework-CalendarStore==7.3-pyobjc-framework-CallKit==7.3-pyobjc-framework-CFNetwork==7.3-pyobjc-framework-ClassKit==7.3-pyobjc-framework-CloudKit==7.3-pyobjc-framework-Cocoa==7.3-pyobjc-framework-Collaboration==7.3-pyobjc-framework-ColorSync==7.3-pyobjc-framework-Contacts==7.3-pyobjc-framework-ContactsUI==7.3-pyobjc-framework-CoreAudio==7.3-pyobjc-framework-CoreAudioKit==7.3-pyobjc-framework-CoreBluetooth==7.3-pyobjc-framework-CoreData==7.3-pyobjc-framework-CoreHaptics==7.3-pyobjc-framework-CoreLocation==7.3-pyobjc-framework-CoreMedia==7.3-pyobjc-framework-CoreMediaIO==7.3-pyobjc-framework-CoreMIDI==7.3-pyobjc-framework-CoreML==7.3-pyobjc-framework-CoreMotion==7.3-pyobjc-framework-CoreServices==7.3-pyobjc-framework-CoreSpotlight==7.3-pyobjc-framework-CoreText==7.3-pyobjc-framework-CoreWLAN==7.3-pyobjc-framework-CryptoTokenKit==7.3-pyobjc-framework-DeviceCheck==7.3-pyobjc-framework-DictionaryServices==7.3-pyobjc-framework-DiscRecording==7.3-pyobjc-framework-DiscRecordingUI==7.3-pyobjc-framework-DiskArbitration==7.3-pyobjc-framework-DVDPlayback==7.3-pyobjc-framework-EventKit==7.3-pyobjc-framework-ExceptionHandling==7.3-pyobjc-framework-ExecutionPolicy==7.3-pyobjc-framework-ExternalAccessory==7.3-pyobjc-framework-FileProvider==7.3-pyobjc-framework-FileProviderUI==7.3-pyobjc-framework-FinderSync==7.3-pyobjc-framework-FSEvents==7.3-pyobjc-framework-GameCenter==7.3-pyobjc-framework-GameController==7.3-pyobjc-framework-GameKit==7.3-pyobjc-framework-GameplayKit==7.3-pyobjc-framework-ImageCaptureCore==7.3-pyobjc-framework-IMServicePlugIn==7.3-pyobjc-framework-InputMethodKit==7.3-pyobjc-framework-InstallerPlugins==7.3-pyobjc-framework-InstantMessage==7.3-pyobjc-framework-Intents==7.3-pyobjc-framework-IOSurface==7.3-pyobjc-framework-iTunesLibrary==7.3-pyobjc-framework-KernelManagement==7.3-pyobjc-framework-LatentSemanticMapping==7.3-pyobjc-framework-LaunchServices==7.3-pyobjc-framework-libdispatch==7.3-pyobjc-framework-LinkPresentation==7.3-pyobjc-framework-LocalAuthentication==7.3-pyobjc-framework-MapKit==7.3-pyobjc-framework-MediaAccessibility==7.3-pyobjc-framework-MediaLibrary==7.3-pyobjc-framework-MediaPlayer==7.3-pyobjc-framework-MediaToolbox==7.3-pyobjc-framework-Metal==7.3-pyobjc-framework-MetalKit==7.3-pyobjc-framework-MetalPerformanceShaders==7.3-pyobjc-framework-MetalPerformanceShadersGraph==7.3-pyobjc-framework-MLCompute==7.3-pyobjc-framework-ModelIO==7.3-pyobjc-framework-MultipeerConnectivity==7.3-pyobjc-framework-NaturalLanguage==7.3-pyobjc-framework-NetFS==7.3-pyobjc-framework-Network==7.3-pyobjc-framework-NetworkExtension==7.3-pyobjc-framework-NotificationCenter==7.3-pyobjc-framework-OpenDirectory==7.3-pyobjc-framework-OSAKit==7.3-pyobjc-framework-OSLog==7.3-pyobjc-framework-PassKit==7.3-pyobjc-framework-PencilKit==7.3-pyobjc-framework-Photos==7.3-pyobjc-framework-PhotosUI==7.3-pyobjc-framework-PreferencePanes==7.3-pyobjc-framework-PushKit==7.3-pyobjc-framework-Quartz==7.3-pyobjc-framework-QuickLookThumbnailing==7.3-pyobjc-framework-ReplayKit==7.3-pyobjc-framework-SafariServices==7.3-pyobjc-framework-SceneKit==7.3-pyobjc-framework-ScreenSaver==7.3-pyobjc-framework-ScreenTime==7.3-pyobjc-framework-ScriptingBridge==7.3-pyobjc-framework-SearchKit==7.3-pyobjc-framework-Security==7.3-pyobjc-framework-SecurityFoundation==7.3-pyobjc-framework-SecurityInterface==7.3-pyobjc-framework-ServiceManagement==7.3-pyobjc-framework-Social==7.3-pyobjc-framework-SoundAnalysis==7.3-pyobjc-framework-Speech==7.3-pyobjc-framework-SpriteKit==7.3-pyobjc-framework-StoreKit==7.3-pyobjc-framework-SyncServices==7.3-pyobjc-framework-SystemConfiguration==7.3-pyobjc-framework-SystemExtensions==7.3-pyobjc-framework-UniformTypeIdentifiers==7.3-pyobjc-framework-UserNotifications==7.3-pyobjc-framework-UserNotificationsUI==7.3-pyobjc-framework-VideoSubscriberAccount==7.3-pyobjc-framework-VideoToolbox==7.3-pyobjc-framework-Virtualization==7.3-pyobjc-framework-Vision==7.3-pyobjc-framework-WebKit==7.3-pyOpenSSL==23.0.0-pyparsing==3.0.9-pypi-search==2.0-pyproj==3.4.0-PyQt5==5.15.10-PyQt5-Qt5==5.15.13-PyQt5-sip==12.13.0-pyserial==3.5-pyshp==2.3.1-PySocks==1.7.1-python-bidi==0.4.2-python-dateutil==2.8.2-python-dotenv==1.0.1-python-gitlab==4.4.0-python-pptx==0.6.23-python-vlc==3.0.20123-pytz==2022.7.1-PyVirtualDisplay==3.0-pyxlsb==1.0.10-PyYAML==6.0-pyzmq==25.0.0-questplus==2023.1-rasterio==1.3.10-ray==2.10.0-referencing==0.34.0-regex==2023.12.25-requests==2.28.2-requests-toolbelt==1.0.0-rich==13.7.1-rpds-py==0.18.0-rsa==4.9-Rtree==1.0.1-safetensors==0.4.2-SALib==1.4.7-scikit-learn==1.2.1-scipy==1.10.0-seaborn==0.13.2-selenium==4.26.0-sentencepiece==0.1.99-sentry-sdk==1.45.0-setproctitle==1.3.3-Shapely==1.8.2-six==1.16.0-smart-open==7.0.4-smmap==5.0.1-sniffio==1.3.1-snuggs==1.4.7-sortedcontainers==2.4.0-soundfile==0.12.1-soupsieve==2.5-sparse==0.13.0-stable_baselines3==2.3.2-stack-data==0.6.2-starlette==0.37.2-statsmodels==0.13.5-sympy==1.12-tables==3.7.0-tabulate==0.9.0-tblib==1.7.0-tensorboard==2.16.2-tensorboard-data-server==0.7.2-TextTest==4.3.1-textual==0.58.0-threadpoolctl==3.1.0-tinycss2==1.2.1-tokenizers==0.15.2-tomli==2.0.1-toolz==0.12.0-torch==2.4.1-torch_geometric==2.5.3-torchvision==0.19.1-tornado==6.2-tqdm==4.64.1-traitlets==5.9.0-transformers==4.38.2-trio==0.27.0-trio-websocket==0.11.1-typing_extensions==4.12.2-tzdata==2024.1-uc-micro-py==1.0.3-ujson==5.9.0-urllib3==1.26.14-uvicorn==0.29.0-uvloop==0.19.0-virtualenv==20.25.1-wandb==0.16.6-watchfiles==0.21.0-wcwidth==0.2.6-webencodings==0.5.1-websocket-client==1.8.0-websockets==12.0-Werkzeug==3.0.1-wrapt==1.16.0-wsproto==1.2.0-wxPython==4.2.1-xarray==2023.2.0-xlrd==2.0.1-XlsxWriter==3.0.8-xmlrunner==1.7.7-xmlschema==3.3.1-xyzservices==2023.2.0-yarg==0.1.9-yarl==1.9.4-zict==2.2.0-zipp==3.14.0-zope.event==5.0-zope.interface==6.3diff --git a/src/dom/service.py b/src/dom/service.pyindex 9e36e8670..c8a4f0efb 100644--- a/src/dom/service.py+++ b/src/dom/service.py@@ -2,7 +2,7 @@Dom Service"""-from bs4 import BeautifulSoup, NavigableString, Tag+from bs4 import BeautifulSoup, NavigableString, PageElement, Tagfrom pydantic import BaseModelfrom selenium import webdriver@@ -31,32 +31,33 @@ class DomService:# Parse HTML content using BeautifulSoupsoup = BeautifulSoup(html_content, 'html.parser')- candidate_elements: list[tuple[Tag | NavigableString, int]] = [] # (element, depth)- dom_queue = [- (element, 0) for element in (soup.body.children if soup.body else [])- ] # (element, depth)+ candidate_elements: list[Tag | NavigableString] = []+ dom_queue = [element for element in soup.body.children] if soup.body else []xpath_cache = {}# Find candidate elementswhile dom_queue:- element, depth = dom_queue.pop()+ element = dom_queue.pop()should_add_element = False# Handle both Tag elements and text nodesif isinstance(element, Tag):- if self._is_element_accepted(element):- # Add children to queue in reverse order with increased depth- for child in reversed(list(element.children)):- dom_queue.append((child, depth + 1))-- # Check if element is interactive or leaf element- if self._is_interactive_element(element) or self._is_leaf_element(element):- if (- self._is_active(element)- and self._is_top_element(element)- and self._is_visible(element)- ):- should_add_element = True+ if not self._is_element_accepted(element):+ # Skip element if it's not accepted+ element.decompose() # get rid of some memory leaks potentially+ continue++ for child in element.children:+ dom_queue.append(child)++ # Check if element is interactive or leaf element+ if self._is_interactive_element(element) or self._is_leaf_element(element):+ if (+ self._is_active(element)+ and self._is_top_element(element)+ and self._is_visible(element)+ ):+ should_add_element = Trueelif isinstance(element, NavigableString) and element.strip():if self._is_visible(element):@@ -65,15 +66,13 @@ class DomService:if should_add_element:if not isinstance(element, (Tag, NavigableString)):continue- candidate_elements.append((element, depth))+ candidate_elements.append(element)# Process candidatesselector_map: dict[int, str] = {}output_string = ''- for index, (element, depth) in enumerate(candidate_elements):- indent = '\t' * depth # Create indentation based on depth-+ for index, element in enumerate(candidate_elements):xpath = xpath_cache.get(element)if not xpath:xpath = self._generate_xpath(element)@@ -81,28 +80,44 @@ class DomService:# Skip text nodes that are direct children of already processed elementsif isinstance(element, NavigableString) and element.parent in [- e for e, _ in candidate_elements+ e for e in candidate_elements]:continueif isinstance(element, NavigableString):text_content = element.strip()if text_content:- output_string += f'{index}:{indent}{text_content}\n'+ output_string += f'{index}:{text_content}\n'else:+ text_content = self._extract_text_from_all_children(element)+tag_name = element.nameattributes = self._get_essential_attributes(element)opening_tag = f"<{tag_name}{' ' + attributes if attributes else ''}>"closing_tag = f'</{tag_name}>'- text_content = element.get_text().strip() or ''- output_string += f'{index}:{indent}{opening_tag}{text_content}{closing_tag}\n'+ output_string += f'{index}:{opening_tag}{text_content}{closing_tag}\n'selector_map[index] = xpathreturn ProcessedDomContent(output_string=output_string, selector_map=selector_map)+ 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'):+ # element.parser.BUTTON_TAGS = set()++ text_content = ''+ for child in element.descendants:+ if isinstance(child, NavigableString):+ current_child_text = child.strip()+ else:+ current_child_text = child.get_text(strip=True)++ text_content += '\n' + current_child_text+ return text_content.strip() or ''+def _is_interactive_element(self, element: Tag) -> bool:"""Check if element is interactive based on tag name and attributes."""interactive_elements = {@@ -166,7 +181,7 @@ class DomService:return Falsedef _is_element_accepted(self, element: Tag) -> bool:- """Check if element is accepted based on tag name."""+ """Check if element is accepted based on tag name (svg, iframe, script, style, link)."""leaf_element_deny_list = {'svg', 'iframe', 'script', 'style', 'link'}# First check if it's in deny listdiff --git a/src/dom/tests/service_test.py b/src/dom/tests/service_test.pyindex 813e49726..c23f109e4 100644--- a/src/dom/tests/service_test.py+++ b/src/dom/tests/service_test.py@@ -1,16 +1,32 @@import time+from selenium.webdriver.common.by import By+from selenium.webdriver.support import expected_conditions as EC+from selenium.webdriver.support.ui import WebDriverWait+from tokencost import count_string_tokens+from src.dom.service import DomServicefrom src.driver.service import DriverServicedef test_process_html_file():- driver = DriverService().get_driver()+ driver = DriverService(headless=False).get_driver()driver.get('https://www.kayak.ch')# driver.get('https://example.com/')- time.sleep(5)+ # driver.implicitly_wait(5)++ # Wait for accept cookies button to appear+ accept_cookies_button = WebDriverWait(driver, 10).until(+ EC.presence_of_element_located(+ (By.XPATH, '/html/body/div[4]/div/div[2]/div/div/div[3]/div/div[1]/button[1]/div/div')+ )+ )+ accept_cookies_button.click()++ # Wait for banner to disappear+ time.sleep(1)# Process the HTML filedom_service = DomService(driver)@@ -18,4 +34,6 @@ def test_process_html_file():# Add assertions based on expected content of page.htmlprint(f'Processed DOM content: {result.output_string}')- print(f'Selector map: {result.selector_map}')+ # print(f'Selector map: {result.selector_map}')++ print('Tokens:', count_string_tokens(result.output_string, 'gpt-4o'))diff --git a/src/driver/service.py b/src/driver/service.pyindex 1b27bbba8..6ed9e3da4 100644--- a/src/driver/service.py+++ b/src/driver/service.py@@ -14,29 +14,59 @@ class DriverService:def get_driver(self) -> webdriver.Chrome:"""- Sets up and returns a Selenium WebDriver instance.-- Args:- headless (bool): Whether to run browser in headless mode+ Sets up and returns a Selenium WebDriver instance with anti-detection measures.Returns:webdriver.Chrome: Configured Chrome WebDriver instance"""- # Configure Chrome optionschrome_options = Options()if self.headless:chrome_options.add_argument('--headless')- # Disable automation flags+ # Anti-detection measureschrome_options.add_argument('--disable-blink-features=AutomationControlled')chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])chrome_options.add_experimental_option('useAutomationExtension', False)++ # Additional stealth settingschrome_options.add_argument('--start-maximized')- chrome_options.add_argument('--force-device-scale-factor=1')+ chrome_options.add_argument('--disable-extensions')+ chrome_options.add_argument('--no-sandbox')+ chrome_options.add_argument('--disable-infobars')# Initialize the Chrome driverdriver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)+ # Execute stealth scripts+ driver.execute_cdp_cmd(+ 'Page.addScriptToEvaluateOnNewDocument',+ {+ 'source': """+ Object.defineProperty(navigator, 'webdriver', {+ get: () => undefined+ });++ Object.defineProperty(navigator, 'languages', {+ get: () => ['en-US', 'en']+ });++ Object.defineProperty(navigator, 'plugins', {+ get: () => [1, 2, 3, 4, 5]+ });++ window.chrome = {+ runtime: {}+ };++ Object.defineProperty(navigator, 'permissions', {+ get: () => ({+ query: Promise.resolve.bind(Promise)+ })+ });+ """+ },+ )+return driver