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
Core function to scroll up and down on page
magmueller1e9dee081bea
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.pyindex 32d9cac7e..15d4b3df8 100644--- a/browser_use/controller/service.py+++ b/browser_use/controller/service.py@@ -1,6 +1,8 @@import loggingfrom main_content_extractor import MainContentExtractor+from selenium.webdriver.common.by import By+from selenium.webdriver.common.keys import Keysfrom browser_use.agent.views import ActionModel, ActionResultfrom browser_use.browser.service import Browser@@ -13,6 +15,7 @@ from browser_use.controller.views import (GoToUrlAction,InputTextAction,OpenTabAction,+ ScrollDownAction,SearchGoogleAction,SwitchTabAction,)@@ -143,6 +146,29 @@ class Controller:logger.info(f'✅ Done on page {browser._cached_state.url}\n\n: {params.text}')return ActionResult(is_done=True, extracted_content=params.text)+ @self.registry.action(+ 'Scroll down the page by pixel amount - if no amount is specified, scroll down one page',+ param_model=ScrollDownAction,+ requires_browser=True,+ )+ def scroll_down(params: ScrollDownAction, browser: Browser):+ driver = browser._get_driver()+ if params.amount is not None:+ driver.execute_script(f'window.scrollBy(0, {params.amount});')+ else:+ body = driver.find_element(By.TAG_NAME, 'body')+ body.send_keys(Keys.PAGE_DOWN)++ # scroll up+ @self.registry.action(+ 'Scroll up the page by pixel amount',+ param_model=ScrollDownAction,+ requires_browser=True,+ )+ def scroll_up(params: ScrollDownAction, browser: Browser):+ driver = browser._get_driver()+ driver.execute_script(f'window.scrollBy(0, -{params.amount});')+def action(self, description: str, **kwargs):"""Decorator for registering custom actionsdiff --git a/browser_use/controller/views.py b/browser_use/controller/views.pyindex 8d1b634c1..342647480 100644--- a/browser_use/controller/views.py+++ b/browser_use/controller/views.py@@ -1,4 +1,4 @@-from typing import Literal+from typing import Literal, Optionalfrom pydantic import BaseModel@@ -36,3 +36,9 @@ class OpenTabAction(BaseModel):class ExtractPageContentAction(BaseModel):value: Literal['text', 'markdown', 'html'] = 'text'+++class ScrollDownAction(BaseModel):+ amount: Optional[int] = (+ None # The number of pixels to scroll down. If None, scroll down one page+ )diff --git a/examples/scrolling_page.py b/examples/scrolling_page.pynew file mode 100644index 000000000..3f81be577--- /dev/null+++ b/examples/scrolling_page.py@@ -0,0 +1,32 @@+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++import asyncio++from langchain_openai import ChatOpenAI++from browser_use import Agent++"""+Example: Using the 'Scroll down' action.++This script demonstrates how the agent can navigate to a webpage and scroll down the content.+If no amount is specified, the agent will scroll down by one page height.+"""++llm = ChatOpenAI(model='gpt-4o')++agent = Agent(+ task="Navigate to 'https://en.wikipedia.org/wiki/Internet' and scroll down by one page - then scroll up by 100 pixels - then scroll down by 100 pixels - then scroll down by 10000 pixels.",+ llm=llm,+)+++async def main():+ await agent.run()+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/tests/test_core_functionality.py b/tests/test_core_functionality.pyindex 79e4a13d2..e47c296dc 100644--- a/tests/test_core_functionality.py+++ b/tests/test_core_functionality.py@@ -155,3 +155,34 @@ async def test_done_action(llm, controller):action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]assert 'go_to_url' in action_namesassert 'done' in action_names+++# run with: pytest -k test_scroll_down+async def test_scroll_down(llm, controller):+ """Test 'Scroll down' action and validate that the page actually scrolled"""+ agent = Agent(+ task="Go to 'https://en.wikipedia.org/wiki/Internet' and scroll down the page.",+ llm=llm,+ controller=controller,+ )+ # Get the browser instance+ browser = controller.browser+ driver = browser._get_driver()++ # Navigate to the page and get initial scroll position+ await agent.run(max_steps=1)+ initial_scroll_position = driver.execute_script('return window.pageYOffset;')++ # Perform the scroll down action+ await agent.run(max_steps=2)+ final_scroll_position = driver.execute_script('return window.pageYOffset;')++ # Validate that the scroll position has changed+ assert final_scroll_position > initial_scroll_position, 'Page did not scroll down'++ # Validate that the 'scroll_down' action was executed+ history = agent.history+ actions = [h.model_output.action for h in history if h.model_output and h.model_output.action]+ action_names = [list(action.model_dump(exclude_unset=True).keys())[0] for action in actions]+ assert 'scroll_down' in action_names