libs/langchain/langchain_classic/chains/natbot/crawler.py PYTHON 476 lines View on github.com → Search inside
1import logging2import time3from sys import platform4from typing import (5    TYPE_CHECKING,6    Any,7    TypedDict,8)910if TYPE_CHECKING:11    from playwright.sync_api import Browser, CDPSession, Page1213logger = logging.getLogger(__name__)1415black_listed_elements: set[str] = {16    "html",17    "head",18    "title",19    "meta",20    "iframe",21    "body",22    "script",23    "style",24    "path",25    "svg",26    "br",27    "::marker",28}293031class ElementInViewPort(TypedDict):32    """A typed dictionary containing information about elements in the viewport."""3334    node_index: str35    backend_node_id: int36    node_name: str | None37    node_value: str | None38    node_meta: list[str]39    is_clickable: bool40    origin_x: int41    origin_y: int42    center_x: int43    center_y: int444546class Crawler:47    """A crawler for web pages.4849    **Security Note**: This is an implementation of a crawler that uses a browser via50        Playwright.5152        This crawler can be used to load arbitrary webpages INCLUDING content53        from the local file system.5455        Control access to who can submit crawling requests and what network access56        the crawler has.5758        Make sure to scope permissions to the minimal permissions necessary for59        the application.6061        See https://docs.langchain.com/oss/python/security-policy for more information.62    """6364    def __init__(self) -> None:65        """Initialize the crawler."""66        try:67            from playwright.sync_api import sync_playwright68        except ImportError as e:69            msg = (70                "Could not import playwright python package. "71                "Please install it with `pip install playwright`."72            )73            raise ImportError(msg) from e74        self.browser: Browser = (75            sync_playwright().start().chromium.launch(headless=False)76        )77        self.page: Page = self.browser.new_page()78        self.page.set_viewport_size({"width": 1280, "height": 1080})79        self.page_element_buffer: dict[int, ElementInViewPort]80        self.client: CDPSession8182    def go_to_page(self, url: str) -> None:83        """Navigate to the given URL.8485        Args:86            url: The URL to navigate to. If it does not contain a scheme, it will be87                prefixed with "http://".88        """89        self.page.goto(url=url if "://" in url else "http://" + url)90        self.client = self.page.context.new_cdp_session(self.page)91        self.page_element_buffer = {}9293    def scroll(self, direction: str) -> None:94        """Scroll the page in the given direction.9596        Args:97            direction: The direction to scroll in, either "up" or "down".98        """99        if direction == "up":100            self.page.evaluate(101                "(document.scrollingElement || document.body).scrollTop = "102                "(document.scrollingElement || document.body).scrollTop - "103                "window.innerHeight;"104            )105        elif direction == "down":106            self.page.evaluate(107                "(document.scrollingElement || document.body).scrollTop = "108                "(document.scrollingElement || document.body).scrollTop + "109                "window.innerHeight;"110            )111112    def click(self, id_: str | int) -> None:113        """Click on an element with the given id.114115        Args:116            id_: The id of the element to click on.117        """118        # Inject javascript into the page which removes the target= attribute from links119        js = """120		links = document.getElementsByTagName("a");121		for (var i = 0; i < links.length; i++) {122			links[i].removeAttribute("target");123		}124		"""125        self.page.evaluate(js)126127        element = self.page_element_buffer.get(int(id_))128        if element:129            x: float = element["center_x"]130            y: float = element["center_y"]131132            self.page.mouse.click(x, y)133        else:134            print("Could not find element")  # noqa: T201135136    def type(self, id_: str | int, text: str) -> None:137        """Type text into an element with the given id.138139        Args:140            id_: The id of the element to type into.141            text: The text to type into the element.142        """143        self.click(id_)144        self.page.keyboard.type(text)145146    def enter(self) -> None:147        """Press the Enter key."""148        self.page.keyboard.press("Enter")149150    def crawl(self) -> list[str]:151        """Crawl the current page.152153        Returns:154            A list of the elements in the viewport.155        """156        page = self.page157        page_element_buffer = self.page_element_buffer158        start = time.time()159160        page_state_as_text = []161162        device_pixel_ratio: float = page.evaluate("window.devicePixelRatio")163        if platform == "darwin" and device_pixel_ratio == 1:  # lies164            device_pixel_ratio = 2165166        win_upper_bound: float = page.evaluate("window.pageYOffset")167        win_left_bound: float = page.evaluate("window.pageXOffset")168        win_width: float = page.evaluate("window.screen.width")169        win_height: float = page.evaluate("window.screen.height")170        win_right_bound: float = win_left_bound + win_width171        win_lower_bound: float = win_upper_bound + win_height172173        percentage_progress_start = 1174        percentage_progress_end = 2175176        page_state_as_text.append(177            {178                "x": 0,179                "y": 0,180                "text": f"[scrollbar {percentage_progress_start:0.2f}-"181                f"{percentage_progress_end:0.2f}%]",182            }183        )184185        tree = self.client.send(186            "DOMSnapshot.captureSnapshot",187            {"computedStyles": [], "includeDOMRects": True, "includePaintOrder": True},188        )189        strings: dict[int, str] = tree["strings"]190        document: dict[str, Any] = tree["documents"][0]191        nodes: dict[str, Any] = document["nodes"]192        backend_node_id: dict[int, int] = nodes["backendNodeId"]193        attributes: dict[int, dict[int, Any]] = nodes["attributes"]194        node_value: dict[int, int] = nodes["nodeValue"]195        parent: dict[int, int] = nodes["parentIndex"]196        node_names: dict[int, int] = nodes["nodeName"]197        is_clickable: set[int] = set(nodes["isClickable"]["index"])198199        input_value: dict[str, Any] = nodes["inputValue"]200        input_value_index: list[int] = input_value["index"]201        input_value_values: list[int] = input_value["value"]202203        layout: dict[str, Any] = document["layout"]204        layout_node_index: list[int] = layout["nodeIndex"]205        bounds: dict[int, list[float]] = layout["bounds"]206207        cursor: int = 0208209        child_nodes: dict[str, list[dict[str, Any]]] = {}210        elements_in_view_port: list[ElementInViewPort] = []211212        anchor_ancestry: dict[str, tuple[bool, int | None]] = {"-1": (False, None)}213        button_ancestry: dict[str, tuple[bool, int | None]] = {"-1": (False, None)}214215        def convert_name(216            node_name: str | None,217            has_click_handler: bool | None,  # noqa: FBT001218        ) -> str:219            if node_name == "a":220                return "link"221            if node_name == "input":222                return "input"223            if node_name == "img":224                return "img"225            if (226                node_name == "button" or has_click_handler227            ):  # found pages that needed this quirk228                return "button"229            return "text"230231        def find_attributes(232            attributes: dict[int, Any], keys: list[str]233        ) -> dict[str, str]:234            values = {}235236            for [key_index, value_index] in zip(*(iter(attributes),) * 2, strict=False):237                if value_index < 0:238                    continue239                key = strings[key_index]240                value = strings[value_index]241242                if key in keys:243                    values[key] = value244                    keys.remove(key)245246                    if not keys:247                        return values248249            return values250251        def add_to_hash_tree(252            hash_tree: dict[str, tuple[bool, int | None]],253            tag: str,254            node_id: int,255            node_name: str | None,256            parent_id: int,257        ) -> tuple[bool, int | None]:258            parent_id_str = str(parent_id)259            if parent_id_str not in hash_tree:260                parent_name = strings[node_names[parent_id]].lower()261                grand_parent_id = parent[parent_id]262263                add_to_hash_tree(264                    hash_tree, tag, parent_id, parent_name, grand_parent_id265                )266267            is_parent_desc_anchor, anchor_id = hash_tree[parent_id_str]268269            # even if the anchor is nested in another anchor, we set the "root" for all270            # descendants to be ::Self271            if node_name == tag:272                value: tuple[bool, int | None] = (True, node_id)273            elif (274                is_parent_desc_anchor275            ):  # reuse the parent's anchor_id (which could be much higher in the tree)276                value = (True, anchor_id)277            else:278                value = (279                    False,280                    None,281                )282                # not a descendant of an anchor, most likely it will become text, an283                # interactive element or discarded284285            hash_tree[str(node_id)] = value286287            return value288289        for index, node_name_index in enumerate(node_names):290            node_parent = parent[index]291            node_name: str | None = strings[node_name_index].lower()292293            is_ancestor_of_anchor, anchor_id = add_to_hash_tree(294                anchor_ancestry, "a", index, node_name, node_parent295            )296297            is_ancestor_of_button, button_id = add_to_hash_tree(298                button_ancestry, "button", index, node_name, node_parent299            )300301            try:302                cursor = layout_node_index.index(index)303                # TODO: replace this with proper cursoring, ignoring the fact this is304                # O(n^2) for the moment305            except ValueError:306                continue307308            if node_name in black_listed_elements:309                continue310311            [x, y, width, height] = bounds[cursor]312            x /= device_pixel_ratio313            y /= device_pixel_ratio314            width /= device_pixel_ratio315            height /= device_pixel_ratio316317            elem_left_bound = x318            elem_top_bound = y319            elem_right_bound = x + width320            elem_lower_bound = y + height321322            partially_is_in_viewport = (323                elem_left_bound < win_right_bound324                and elem_right_bound >= win_left_bound325                and elem_top_bound < win_lower_bound326                and elem_lower_bound >= win_upper_bound327            )328329            if not partially_is_in_viewport:330                continue331332            meta_data: list[str] = []333334            # inefficient to grab the same set of keys for kinds of objects, but it's335            # fine for now336            element_attributes = find_attributes(337                attributes[index], ["type", "placeholder", "aria-label", "title", "alt"]338            )339340            ancestor_exception = is_ancestor_of_anchor or is_ancestor_of_button341            ancestor_node_key = (342                None343                if not ancestor_exception344                else str(anchor_id)345                if is_ancestor_of_anchor346                else str(button_id)347            )348            ancestor_node = (349                None350                if not ancestor_exception351                else child_nodes.setdefault(str(ancestor_node_key), [])352            )353354            if node_name == "#text" and ancestor_exception and ancestor_node:355                text = strings[node_value[index]]356                if text in {"|", "•"}:357                    continue358                ancestor_node.append({"type": "type", "value": text})359            else:360                if (361                    node_name == "input" and element_attributes.get("type") == "submit"362                ) or node_name == "button":363                    node_name = "button"364                    element_attributes.pop(365                        "type", None366                    )  # prevent [button ... (button)..]367368                for key in element_attributes:369                    if ancestor_exception and ancestor_node:370                        ancestor_node.append(371                            {372                                "type": "attribute",373                                "key": key,374                                "value": element_attributes[key],375                            }376                        )377                    else:378                        meta_data.append(element_attributes[key])379380            element_node_value = None381382            if node_value[index] >= 0:383                element_node_value = strings[node_value[index]]384                if (385                    element_node_value == "|"386                    # commonly used as a separator, does not add much context - lets387                    # save ourselves some token space388                ):389                    continue390            elif (391                node_name == "input"392                and index in input_value_index393                and element_node_value is None394            ):395                node_input_text_index = input_value_index.index(index)396                text_index = input_value_values[node_input_text_index]397                if node_input_text_index >= 0 and text_index >= 0:398                    element_node_value = strings[text_index]399400            # remove redundant elements401            if ancestor_exception and (node_name not in {"a", "button"}):402                continue403404            elements_in_view_port.append(405                {406                    "node_index": str(index),407                    "backend_node_id": backend_node_id[index],408                    "node_name": node_name,409                    "node_value": element_node_value,410                    "node_meta": meta_data,411                    "is_clickable": index in is_clickable,412                    "origin_x": int(x),413                    "origin_y": int(y),414                    "center_x": int(x + (width / 2)),415                    "center_y": int(y + (height / 2)),416                }417            )418419        # lets filter further to remove anything that does not hold any text nor has420        # click handlers + merge text from leaf#text nodes with the parent421        elements_of_interest = []422        id_counter = 0423424        for element in elements_in_view_port:425            node_index = element.get("node_index")426            node_name = element.get("node_name")427            element_node_value = element.get("node_value")428            node_is_clickable = element.get("is_clickable")429            node_meta_data: list[str] | None = element.get("node_meta")430431            inner_text = f"{element_node_value} " if element_node_value else ""432            meta = ""433434            if node_index in child_nodes:435                for child in child_nodes[node_index]:436                    entry_type = child.get("type")437                    entry_value = child.get("value")438439                    if entry_type == "attribute" and node_meta_data:440                        entry_key = child.get("key")441                        node_meta_data.append(f'{entry_key}="{entry_value}"')442                    else:443                        inner_text += f"{entry_value} "444445            if node_meta_data:446                meta_string = " ".join(node_meta_data)447                meta = f" {meta_string}"448449            if inner_text != "":450                inner_text = f"{inner_text.strip()}"451452            converted_node_name = convert_name(node_name, node_is_clickable)453454            # not very elegant, more like a placeholder455            if (456                (converted_node_name != "button" or meta == "")457                and converted_node_name not in {"link", "input", "img", "textarea"}458            ) and inner_text.strip() == "":459                continue460461            page_element_buffer[id_counter] = element462463            if inner_text != "":464                elements_of_interest.append(465                    f"<{converted_node_name} id={id_counter}{meta}>{inner_text}"466                    f"</{converted_node_name}>"467                )468            else:469                elements_of_interest.append(470                    f"""<{converted_node_name} id={id_counter}{meta}/>"""471                )472            id_counter += 1473474        print(f"Parsing time: {time.time() - start:0.2f} seconds")  # noqa: T201475        return elements_of_interest

Code quality findings 3

Ensure functions have docstrings for documentation
info maintainability missing-docstring
def convert_name(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def find_attributes(
Ensure functions have docstrings for documentation
info maintainability missing-docstring
def add_to_hash_tree(

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings