|
| 1 | +import re |
| 2 | + |
| 3 | +from bs4 import BeautifulSoup |
| 4 | +from selenium import webdriver |
| 5 | +from selenium.webdriver.chrome.options import Options |
| 6 | +from selenium.webdriver.common.by import By |
| 7 | +from typing import Optional, Union, Dict |
| 8 | + |
| 9 | +from autogen.browser_utils.abstract_browser import AbstractBrowser |
| 10 | + |
| 11 | +# Optional PDF support |
| 12 | +IS_PDF_CAPABLE = False |
| 13 | +try: |
| 14 | + import pdfminer |
| 15 | + import pdfminer.high_level |
| 16 | + |
| 17 | + IS_PDF_CAPABLE = True |
| 18 | +except ModuleNotFoundError: |
| 19 | + pass |
| 20 | + |
| 21 | +# Other optional dependencies |
| 22 | +try: |
| 23 | + import pathvalidate |
| 24 | +except ModuleNotFoundError: |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +class HeadlessChromeBrowser(AbstractBrowser): |
| 29 | + """(In preview) A Selenium powered headless Chrome browser. Suitable for Agentic use.""" |
| 30 | + |
| 31 | + def __init__( |
| 32 | + self, |
| 33 | + start_page: Optional[str] = "about:blank", |
| 34 | + viewport_size: Optional[int] = 1024 * 8, |
| 35 | + downloads_folder: Optional[Union[str, None]] = None, |
| 36 | + bing_api_key: Optional[Union[str, None]] = None, |
| 37 | + request_kwargs: Optional[Union[Dict, None]] = None, |
| 38 | + ): |
| 39 | + self.start_page = start_page |
| 40 | + self.driver = None |
| 41 | + self.viewport_size = viewport_size # Applies only to the standard uri types |
| 42 | + self.downloads_folder = downloads_folder |
| 43 | + self.history = list() |
| 44 | + self.page_title = None |
| 45 | + self.viewport_current_page = 0 |
| 46 | + self.viewport_pages = list() |
| 47 | + self.bing_api_key = bing_api_key |
| 48 | + self.request_kwargs = request_kwargs |
| 49 | + self._page_content = "" |
| 50 | + |
| 51 | + self._start_browser() |
| 52 | + |
| 53 | + def _start_browser(self): |
| 54 | + chrome_options = Options() |
| 55 | + chrome_options.add_argument("--headless") |
| 56 | + self.driver = webdriver.Chrome(options=chrome_options) |
| 57 | + self.driver.get(self.start_page) |
| 58 | + |
| 59 | + @property |
| 60 | + def address(self) -> str: |
| 61 | + return self.driver.current_url |
| 62 | + |
| 63 | + def set_address(self, uri_or_path): |
| 64 | + if uri_or_path.startswith("bing:"): |
| 65 | + self._bing_search(uri_or_path[len("bing:") :].strip()) |
| 66 | + else: |
| 67 | + self.driver.get(uri_or_path) |
| 68 | + |
| 69 | + @property |
| 70 | + def viewport(self) -> str: |
| 71 | + """Return the content of the current viewport.""" |
| 72 | + if not self.viewport_pages: |
| 73 | + return "" |
| 74 | + bounds = self.viewport_pages[self.viewport_current_page] |
| 75 | + return self._page_content[bounds[0] : bounds[1]] |
| 76 | + |
| 77 | + @property |
| 78 | + def page_content(self) -> str: |
| 79 | + """Return the full contents of the current page.""" |
| 80 | + return self._page_content |
| 81 | + |
| 82 | + def _set_page_content(self, content) -> str: |
| 83 | + """Sets the text content of the current page.""" |
| 84 | + self._page_content = content |
| 85 | + self._split_pages() |
| 86 | + if self.viewport_current_page >= len(self.viewport_pages): |
| 87 | + self.viewport_current_page = len(self.viewport_pages) - 1 |
| 88 | + |
| 89 | + def _split_pages(self): |
| 90 | + # Split only regular pages |
| 91 | + if not self.address.startswith("http:") and not self.address.startswith("https:"): |
| 92 | + return |
| 93 | + |
| 94 | + # Handle empty pages |
| 95 | + if len(self._page_content) == 0: |
| 96 | + self.viewport_pages = [(0, 0)] |
| 97 | + return |
| 98 | + |
| 99 | + # Break the viewport into pages |
| 100 | + self.viewport_pages = [] |
| 101 | + start_idx = 0 |
| 102 | + while start_idx < len(self._page_content): |
| 103 | + end_idx = min(start_idx + self.viewport_size, len(self._page_content)) |
| 104 | + self.viewport_pages.append((start_idx, end_idx)) |
| 105 | + start_idx = end_idx |
| 106 | + |
| 107 | + def _process_html(self, html: str) -> str: |
| 108 | + """Process the raw HTML content and return the processed text.""" |
| 109 | + soup = BeautifulSoup(html, "html.parser") |
| 110 | + |
| 111 | + # Remove javascript and style blocks |
| 112 | + for script in soup(["script", "style"]): |
| 113 | + script.extract() |
| 114 | + |
| 115 | + # Convert to text |
| 116 | + text = soup.get_text() |
| 117 | + |
| 118 | + # Remove excessive blank lines |
| 119 | + text = re.sub(r"\n{2,}", "\n\n", text).strip() |
| 120 | + |
| 121 | + return text |
| 122 | + |
| 123 | + def _bing_search(self, query): |
| 124 | + self.driver.get("https://www.bing.com") |
| 125 | + |
| 126 | + search_bar = self.driver.find_element(By.NAME, "q") |
| 127 | + search_bar.clear() |
| 128 | + search_bar.send_keys(query) |
| 129 | + search_bar.submit() |
| 130 | + |
| 131 | + def page_down(self): |
| 132 | + """Move the viewport one page down.""" |
| 133 | + if self.viewport_current_page < len(self.viewport_pages) - 1: |
| 134 | + self.viewport_current_page += 1 |
| 135 | + |
| 136 | + def page_up(self): |
| 137 | + """Move the viewport one page up.""" |
| 138 | + if self.viewport_current_page > 0: |
| 139 | + self.viewport_current_page -= 1 |
| 140 | + |
| 141 | + def visit_page(self, path_or_uri): |
| 142 | + """Update the address, visit the page, and return the content of the viewport.""" |
| 143 | + self.set_address(path_or_uri) |
| 144 | + html = self.driver.execute_script("return document.body.innerHTML;") |
| 145 | + self._set_page_content(self._process_html(html)) |
| 146 | + return self.viewport |
0 commit comments