Skip to content

Python scraper based on AI

fetch node level k implementation

Matteo Vedovati4cb621feab7e
diff --git a/examples/openai/fetch_multiple_links.py b/examples/openai/fetch_multiple_links.py
new file mode 100644
index 00000000..53e246de
--- /dev/null
+++ b/examples/openai/fetch_multiple_links.py
@@ -0,0 +1,21 @@
+
+from scrapegraphai.graphs import DepthSearchGraph
+
+graph_config = {
+ "llm": {
+ "api_key":"YOUR_API_KEY",
+ "model": "openai/gpt-4o-mini",
+ },
+ "verbose": True,
+ "headless": False,
+ "depth": 2,
+}
+
+search_graph = DepthSearchGraph(
+ prompt="List me all the projects with their description",
+ source="https://perinim.github.io/projects/",
+ config=graph_config
+)
+
+result = search_graph.run()
+print(result)
\ No newline at end of file
diff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.py
index efd6bd7e..b5ffcc47 100644
--- a/scrapegraphai/graphs/__init__.py
+++ b/scrapegraphai/graphs/__init__.py
@@ -26,3 +26,4 @@ from .search_link_graph import SearchLinkGraph
from .screenshot_scraper_graph import ScreenshotScraperGraph
from .smart_scraper_multi_concat_graph import SmartScraperMultiConcatGraph
from .code_generator_graph import CodeGeneratorGraph
+from .depth_search_graph import DepthSearchGraph
diff --git a/scrapegraphai/graphs/depth_search_graph.py b/scrapegraphai/graphs/depth_search_graph.py
new file mode 100644
index 00000000..a96d96a7
--- /dev/null
+++ b/scrapegraphai/graphs/depth_search_graph.py
@@ -0,0 +1,96 @@
+"""
+... Module
+"""
+from typing import Optional
+import logging
+from pydantic import BaseModel
+from .base_graph import BaseGraph
+from .abstract_graph import AbstractGraph
+from ..utils.save_code_to_file import save_code_to_file
+from ..nodes import (
+ FetchNodeLevelK
+)
+
+class DepthSearchGraph(AbstractGraph):
+ """
+ CodeGeneratorGraph is a script generator pipeline that generates the function extract_data(html: str) -> dict() for
+ extracting the wanted information from a HTML page. The code generated is in Python and uses the library BeautifulSoup.
+ It requires a user prompt, a source URL, and an output schema.
+
+ Attributes:
+ prompt (str): The prompt for the graph.
+ source (str): The source of the graph.
+ config (dict): Configuration parameters for the graph.
+ schema (BaseModel): The schema for the graph output.
+ llm_model: An instance of a language model client, configured for generating answers.
+ embedder_model: An instance of an embedding model client,
+ configured for generating embeddings.
+ verbose (bool): A flag indicating whether to show print statements during execution.
+ headless (bool): A flag indicating whether to run the graph in headless mode.
+ library (str): The library used for web scraping (beautiful soup).
+
+ Args:
+ prompt (str): The prompt for the graph.
+ source (str): The source of the graph.
+ config (dict): Configuration parameters for the graph.
+ schema (BaseModel): The schema for the graph output.
+
+ Example:
+ >>> code_gen = CodeGeneratorGraph(
+ ... "List me all the attractions in Chioggia.",
+ ... "https://en.wikipedia.org/wiki/Chioggia",
+ ... {"llm": {"model": "openai/gpt-3.5-turbo"}}
+ ... )
+ >>> result = code_gen.run()
+ )
+ """
+
+ def __init__(self, prompt: str, source: str, config: dict, schema: Optional[BaseModel] = None):
+
+ super().__init__(prompt, config, source, schema)
+
+ self.input_key = "url" if source.startswith("http") else "local_dir"
+
+ def _create_graph(self) -> BaseGraph:
+ """
+ Creates the graph of nodes representing the workflow for web scraping.
+
+ Returns:
+ BaseGraph: A graph instance representing the web scraping workflow.
+ """
+
+ fetch_node = FetchNodeLevelK(
+ input="url| local_dir",
+ output=["docs"],
+ node_config={
+ "loader_kwargs": self.config.get("loader_kwargs", {}),
+ "force": self.config.get("force", False),
+ "cut": self.config.get("cut", True),
+ "browser_base": self.config.get("browser_base"),
+ "depth": self.config.get("depth", 1)
+ }
+ )
+
+ return BaseGraph(
+ nodes=[
+ fetch_node
+ ],
+ edges=[],
+ entry_point=fetch_node,
+ graph_name=self.__class__.__name__
+ )
+
+ def run(self) -> str:
+ """
+ Executes the scraping process and returns the generated code.
+
+ Returns:
+ str: The generated code.
+ """
+
+ inputs = {"user_prompt": self.prompt, self.input_key: self.source}
+ self.final_state, self.execution_info = self.graph.execute(inputs)
+
+ docs = self.final_state.get("docs", "No docs")
+
+ return docs
\ No newline at end of file
diff --git a/scrapegraphai/nodes/__init__.py b/scrapegraphai/nodes/__init__.py
index e5fafb87..7b994746 100644
--- a/scrapegraphai/nodes/__init__.py
+++ b/scrapegraphai/nodes/__init__.py
@@ -28,6 +28,6 @@ from .html_analyzer_node import HtmlAnalyzerNode
from .generate_code_node import GenerateCodeNode
from .search_node_with_context import SearchLinksWithContext
from .reasoning_node import ReasoningNode
-from .fetch_node_level_k import FetchNodelevelK
+from .fetch_node_level_k import FetchNodeLevelK
from .generate_answer_node_k_level import GenerateAnswerNodeKLevel
from .description_node import DescriptionNode
diff --git a/scrapegraphai/nodes/fetch_node_level_k.py b/scrapegraphai/nodes/fetch_node_level_k.py
index bbaafded..f9fd57a8 100644
--- a/scrapegraphai/nodes/fetch_node_level_k.py
+++ b/scrapegraphai/nodes/fetch_node_level_k.py
@@ -7,6 +7,8 @@ from ..docloaders import ChromiumLoader
from ..utils.cleanup_html import cleanup_html
from ..utils.convert_to_md import convert_to_md
from langchain_core.documents import Document
+from bs4 import BeautifulSoup
+from urllib.parse import quote, urljoin
class FetchNodeLevelK(BaseNode):
"""
@@ -34,8 +36,6 @@ class FetchNodeLevelK(BaseNode):
node_name: str = "FetchLevelK",
):
super().__init__(node_name, "node", input, output, 2, node_config)
-
- self.llm_model = node_config["llm_model"]
self.embedder_model = node_config.get("embedder_model", None)
@@ -56,6 +56,16 @@ class FetchNodeLevelK(BaseNode):
self.browser_base = (
None if node_config is None else node_config.get("browser_base", None)
)
+
+ self.depth = (
+ 1 if node_config is None else node_config.get("depth", 1)
+ )
+
+ self.only_inside_links = (
+ False if node_config is None else node_config.get("only_inside_links", False)
+ )
+
+ self.min_input_len = 1
def execute(self, state: dict) -> dict:
"""
@@ -83,6 +93,8 @@ class FetchNodeLevelK(BaseNode):
source = input_data[0]
+ documents = [{"source": source}]
+
self.logger.info(f"--- (Fetching HTML from: {source}) ---")
loader_kwargs = {}
@@ -90,6 +102,12 @@ class FetchNodeLevelK(BaseNode):
if self.node_config is not None:
loader_kwargs = self.node_config.get("loader_kwargs", {})
+ for _ in range(self.depth):
+ documents = self.obtain_content(documents, loader_kwargs)
+
+ return {self.output_keys[0]: documents}
+
+ def fetch_content(self, source: str, loader_kwargs) -> Optional[str]:
if self.browser_base is not None:
try:
from ..docloaders.browser_base import browser_base_fetch
@@ -108,8 +126,58 @@ class FetchNodeLevelK(BaseNode):
document = loader.load()
- if not document or not document[0].page_content.strip():
- raise ValueError("""No HTML body content found in
- the document fetched by ChromiumLoader.""")
+ return document
+
+ def extract_links(self, html_content: str) -> list:
+ soup = BeautifulSoup(html_content, 'html.parser')
+ links = [link['href'] for link in soup.find_all('a', href=True)]
+ self.logger.info(f"Extracted {len(links)} links.")
+ return links
+
+ def get_full_links(self, base_url: str, links: list) -> list:
+ full_links = []
+ for link in links:
+ if self.only_inside_links and link.startswith("http"):
+ continue
+ full_link = link if link.startswith("http") else urljoin(base_url, link)
+ full_links.append(full_link)
+ return full_links
+
+ def obtain_content(self, documents: List, loader_kwargs) -> List:
+ for doc in documents:
+ source = doc['source']
+ if 'document' not in doc:
+ document = self.fetch_content(source, loader_kwargs)
+
+ if not document or not document[0].page_content.strip():
+ self.logger.warning(f"Failed to fetch content for {source}")
+ documents.remove(doc)
+ continue
+
+ doc['document'] = document[0].page_content
- parsed_content = document[0].page_content
\ No newline at end of file
+ links = self.extract_links(doc['document'])
+ full_links = self.get_full_links(source, links)
+
+ # Check if the links are already present in other documents
+ for link in full_links:
+ # Check if any document is from the same link
+ if not any(d.get('source', '') == link for d in documents):
+ # Add the document
+ documents.append({"source": link})
+
+ return documents
+
+ def process_links(self, base_url: str, links: list, loader_kwargs, depth: int, current_depth: int = 1) -> dict:
+ content_dict = {}
+ for idx, link in enumerate(links, start=1):
+ full_link = link if link.startswith("http") else urljoin(base_url, link)
+ self.logger.info(f"Processing link {idx}: {full_link}")
+ link_content = self.fetch_content(full_link, loader_kwargs)
+
+ if current_depth < depth:
+ new_links = self.extract_links(link_content)
+ content_dict.update(self.process_links(full_link, new_links, depth, current_depth + 1))
+ else:
+ self.logger.warning(f"Failed to fetch content for {full_link}")
+ return content_dict
\ No newline at end of file