#!/usr/bin/env python3 """ Playground script to test the browser-use actor API. This script demonstrates: - Starting a browser session - Using the actor API to navigate and interact - Finding elements, clicking, scrolling, JavaScript evaluation - Testing most of the available methods """ import asyncio import json import logging from browser_use import Browser # Configure logging to see what's happening logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) async def main(): """Main playground function.""" logger.info('๐Ÿš€ Starting browser actor playground') # Create browser session browser = Browser() try: # Start the browser await browser.start() logger.info('โœ… Browser session started') # Navigate to Wikipedia using integrated methods logger.info('๐Ÿ“– Navigating to Wikipedia...') page = await browser.new_page('https://en.wikipedia.org') # Get basic page info url = await page.get_url() title = await page.get_title() logger.info(f'๐Ÿ“„ Page loaded: {title} ({url})') # Take a screenshot logger.info('๐Ÿ“ธ Taking initial screenshot...') screenshot_b64 = await page.screenshot() logger.info(f'๐Ÿ“ธ Screenshot captured: {len(screenshot_b64)} bytes') # Set viewport size logger.info('๐Ÿ–ฅ๏ธ Setting viewport to 1920x1080...') await page.set_viewport_size(1920, 1080) # Execute some JavaScript to count links logger.info('๐Ÿ” Counting article links using JavaScript...') js_code = """() => { // Find all article links on the page const links = Array.from(document.querySelectorAll('a[href*="/wiki/"]:not([href*=":"])')) .filter(link => !link.href.includes('Main_Page') && !link.href.includes('Special:')); return { total: links.length, sample: links.slice(0, 3).map(link => ({ href: link.href, text: link.textContent.trim() })) }; }""" link_info = json.loads(await page.evaluate(js_code)) logger.info(f'๐Ÿ”— Found {link_info["total"]} article links') # Try to find and interact with links using CSS selector try: # Find article links on the page links = await page.get_elements_by_css_selector('a[href*="/wiki/"]:not([href*=":"])') if links: logger.info(f'๐Ÿ“‹ Found {len(links)} wiki links via CSS selector') # Pick the first link link_element = links[0] # Get link info using available methods basic_info = await link_element.get_basic_info() link_href = await link_element.get_attribute('href') logger.info(f'๐ŸŽฏ Selected element: <{basic_info["nodeName"]}>') logger.info(f'๐Ÿ”— Link href: {link_href}') if basic_info['boundingBox']: bbox = basic_info['boundingBox'] logger.info(f'๐Ÿ“ Position: ({bbox["x"]}, {bbox["y"]}) Size: {bbox["width"]}x{bbox["height"]}') # Test element interactions with robust implementations logger.info('๐Ÿ‘† Hovering over the element...') await link_element.hover() await asyncio.sleep(1) logger.info('๐Ÿ” Focusing the element...') await link_element.focus() await asyncio.sleep(0.5) # Click the link using robust click method logger.info('๐Ÿ–ฑ๏ธ Clicking the link with robust fallbacks...') await link_element.click() # Wait for navigation await asyncio.sleep(3) # Get new page info new_url = await page.get_url() new_title = await page.get_title() logger.info(f'๐Ÿ“„ Navigated to: {new_title}') logger.info(f'๐ŸŒ New URL: {new_url}') else: logger.warning('โŒ No links found to interact with') except Exception as e: logger.warning(f'โš ๏ธ Link interaction failed: {e}') # Scroll down the page logger.info('๐Ÿ“œ Scrolling down the page...') mouse = await page.mouse await mouse.scroll(x=0, y=100, delta_y=500) await asyncio.sleep(1) # Test mouse operations logger.info('๐Ÿ–ฑ๏ธ Testing mouse operations...') await mouse.move(x=100, y=200) await mouse.click(x=150, y=250) # Execute more JavaScript examples logger.info('๐Ÿงช Testing JavaScript evaluation...') # Simple expressions page_height = await page.evaluate('() => document.body.scrollHeight') current_scroll = await page.evaluate('() => window.pageYOffset') logger.info(f'๐Ÿ“ Page height: {page_height}px, current scroll: {current_scroll}px') # JavaScript with arguments result = await page.evaluate('(x) => x * 2', 21) logger.info(f'๐Ÿงฎ JavaScript with args: 21 * 2 = {result}') # More complex JavaScript page_stats = json.loads( await page.evaluate("""() => { return { url: window.location.href, title: document.title, links: document.querySelectorAll('a').length, images: document.querySelectorAll('img').length, scrollTop: window.pageYOffset, viewportHeight: window.innerHeight }; }""") ) logger.info(f'๐Ÿ“Š Page stats: {page_stats}') # Get page title using different methods title_via_js = await page.evaluate('() => document.title') title_via_api = await page.get_title() logger.info(f'๐Ÿ“ Title via JS: "{title_via_js}"') logger.info(f'๐Ÿ“ Title via API: "{title_via_api}"') # Take a final screenshot logger.info('๐Ÿ“ธ Taking final screenshot...') final_screenshot = await page.screenshot() logger.info(f'๐Ÿ“ธ Final screenshot: {len(final_screenshot)} bytes') # Test browser navigation with error handling logger.info('โฌ…๏ธ Testing browser back navigation...') try: await page.go_back() await asyncio.sleep(2) back_url = await page.get_url() back_title = await page.get_title() logger.info(f'๐Ÿ“„ After going back: {back_title}') logger.info(f'๐ŸŒ Back URL: {back_url}') except RuntimeError as e: logger.info(f'โ„น๏ธ Navigation back failed as expected: {e}') # Test creating new page logger.info('๐Ÿ†• Creating new blank page...') new_page = await browser.new_page() new_page_url = await new_page.get_url() logger.info(f'๐Ÿ†• New page created with URL: {new_page_url}') # Get all pages all_pages = await browser.get_pages() logger.info(f'๐Ÿ“‘ Total pages: {len(all_pages)}') # Test form interaction if we can find a form try: # Look for search input on the page search_inputs = await page.get_elements_by_css_selector('input[type="search"], input[name*="search"]') if search_inputs: search_input = search_inputs[0] logger.info('๐Ÿ” Found search input, testing form interaction...') await search_input.focus() await search_input.fill('test search query') await page.press('Enter') logger.info('โœ… Form interaction test completed') else: logger.info('โ„น๏ธ No search inputs found for form testing') except Exception as e: logger.info(f'โ„น๏ธ Form interaction test skipped: {e}') # wait 2 seconds before closing the new page logger.info('๐Ÿ•’ Waiting 2 seconds before closing the new page...') await asyncio.sleep(2) logger.info('๐Ÿ—‘๏ธ Closing new page...') await browser.close_page(new_page) logger.info('โœ… Playground completed successfully!') input('Press Enter to continue...') except Exception as e: logger.error(f'โŒ Error in playground: {e}', exc_info=True) finally: # Clean up logger.info('๐Ÿงน Cleaning up...') try: await browser.stop() logger.info('โœ… Browser session stopped') except Exception as e: logger.error(f'โŒ Error stopping browser: {e}') if __name__ == '__main__': asyncio.run(main())