Python scraper based on AI
Python ai-crawlerai-scrapingai-searchcrawlerdata-extractionfirecrawl-alternativelarge-language-modelllmmarkdownragscrapingscraping-pythonweb-crawlerweb-crawlersweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
refactoring of the code
Marco Vinciguerra560f079d4cb2
diff --git a/scrapegraphai/docloaders/browser_base.py b/scrapegraphai/docloaders/browser_base.pyindex c9413d68..cc9e7e85 100644--- a/scrapegraphai/docloaders/browser_base.py+++ b/scrapegraphai/docloaders/browser_base.py@@ -13,8 +13,10 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_cont- `api_key`: The API key provided by BrowserBase.- `project_id`: The ID of the project on BrowserBase where you want to fetch data from.- `link`: The URL or link that you want to fetch data from.- - `text_content`: A boolean flag to specify whether to return only the text content (True) or the full HTML (False).- - `async_mode`: A boolean flag that determines whether the function runs asynchronously (True) or synchronously (False, default).+ - `text_content`: A boolean flag to specify whether to return only the+ text content (True) or the full HTML (False).+ - `async_mode`: A boolean flag that determines whether the function runs asynchronously+ (True) or synchronously (False, default).It initializes a Browserbase object with the given API key and project ID,then uses this object to load the specified link.@@ -37,8 +39,10 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_contapi_key (str): The API key provided by BrowserBase.project_id (str): The ID of the project on BrowserBase where you want to fetch data from.link (str): The URL or link that you want to fetch data from.- text_content (bool): Whether to return only the text content (True) or the full HTML (False). Defaults to True.- async_mode (bool): Whether to run the function asynchronously (True) or synchronously (False). Defaults to False.+ text_content (bool): Whether to return only the text content+ (True) or the full HTML (False). Defaults to True.+ async_mode (bool): Whether to run the function asynchronously+ (True) or synchronously (False). Defaults to False.Returns:object: The result of the loading operation.@@ -47,7 +51,8 @@ def browser_base_fetch(api_key: str, project_id: str, link: List[str], text_conttry:from browserbase import Browserbaseexcept ImportError:- raise ImportError("The browserbase module is not installed. Please install it using `pip install browserbase`.")+ raise ImportError(f"""The browserbase module is not installed.+ Please install it using `pip install browserbase`.""")browserbase = Browserbase(api_key=api_key, project_id=project_id)diff --git a/scrapegraphai/docloaders/scrape_do.py b/scrapegraphai/docloaders/scrape_do.pyindex cd9086c3..467ea0a1 100644--- a/scrapegraphai/docloaders/scrape_do.py+++ b/scrapegraphai/docloaders/scrape_do.py@@ -24,17 +24,14 @@ def scrape_do_fetch(token, target_url, use_proxy=False, geoCode=None, super_prox"""encoded_url = urllib.parse.quote(target_url)if use_proxy:- # Create proxy mode URL- proxyModeUrl = f"http://{token}:@proxy.scrape.do:8080"+ proxy_mode_url = f"http://{token}:@proxy.scrape.do:8080"proxies = {- "http": proxyModeUrl,- "https": proxyModeUrl,+ "http": proxy_mode_url,+ "https": proxy_mode_url,}- # Add optional geoCode and super proxy parameters if providedparams = {"geoCode": geoCode, "super": str(super_proxy).lower()} if geoCode else {}response = requests.get(target_url, proxies=proxies, verify=False, params=params)else:- # API Mode URLurl = f"http://api.scrape.do?token={token}&url={encoded_url}"response = requests.get(url)diff --git a/scrapegraphai/graphs/__init__.py b/scrapegraphai/graphs/__init__.pyindex ebe914fb..9b3f36c3 100644--- a/scrapegraphai/graphs/__init__.py+++ b/scrapegraphai/graphs/__init__.py@@ -26,4 +26,4 @@ from .markdown_scraper_multi_graph import MDScraperMultiGraphfrom .search_link_graph import SearchLinkGraphfrom .screenshot_scraper_graph import ScreenshotScraperGraphfrom .smart_scraper_multi_concat_graph import SmartScraperMultiConcatGraph-from .code_generator_graph import CodeGeneratorGraph\ No newline at end of file+from .code_generator_graph import CodeGeneratorGraphdiff --git a/scrapegraphai/graphs/abstract_graph.py b/scrapegraphai/graphs/abstract_graph.pyindex b546460f..99c13886 100644--- a/scrapegraphai/graphs/abstract_graph.py+++ b/scrapegraphai/graphs/abstract_graph.py@@ -128,7 +128,7 @@ class AbstractGraph(ABC):if requests_per_second is not None:with warnings.catch_warnings():warnings.simplefilter("ignore")- llm_params["rate_limiter"] = InMemoryRateLimiter(requests_per_second=requests_per_second)+ llm_params["rate_limiter"] = InMemoryRateLimiter(requests_per_second=requests_per_second)if max_retries is not None:llm_params["max_retries"] = max_retriesdiff --git a/scrapegraphai/graphs/base_graph.py b/scrapegraphai/graphs/base_graph.pyindex 6d160e37..05f9773c 100644--- a/scrapegraphai/graphs/base_graph.py+++ b/scrapegraphai/graphs/base_graph.py@@ -45,7 +45,8 @@ class BaseGraph:... )"""- def __init__(self, nodes: list, edges: list, entry_point: str, use_burr: bool = False, burr_config: dict = None, graph_name: str = "Custom"):+ def __init__(self, nodes: list, edges: list, entry_point: str,+ use_burr: bool = False, burr_config: dict = None, graph_name: str = "Custom"):self.nodes = nodesself.raw_edges = edgesself.edges = self._create_edges({e for e in edges})diff --git a/scrapegraphai/graphs/code_generator_graph.py b/scrapegraphai/graphs/code_generator_graph.pyindex 9786dc4f..c0c0f52b 100644--- a/scrapegraphai/graphs/code_generator_graph.py+++ b/scrapegraphai/graphs/code_generator_graph.py@@ -51,7 +51,7 @@ class CodeGeneratorGraph(AbstractGraph):"""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"@@ -63,7 +63,7 @@ class CodeGeneratorGraph(AbstractGraph):Returns:BaseGraph: A graph instance representing the web scraping workflow."""-+if self.schema is None:raise KeyError("The schema is required for CodeGeneratorGraph")diff --git a/scrapegraphai/graphs/deep_scraper_graph.py b/scrapegraphai/graphs/deep_scraper_graph.pyindex 404fed9f..f3f2ec2d 100644--- a/scrapegraphai/graphs/deep_scraper_graph.py+++ b/scrapegraphai/graphs/deep_scraper_graph.py@@ -134,7 +134,6 @@ class DeepScraperGraph(AbstractGraph):)-def _create_graph(self) -> BaseGraph:"""Creates the graph of nodes representing the workflow for web scrapingdiff --git a/scrapegraphai/graphs/omni_search_graph.py b/scrapegraphai/graphs/omni_search_graph.pyindex 807a5b0a..41d35ab7 100644--- a/scrapegraphai/graphs/omni_search_graph.py+++ b/scrapegraphai/graphs/omni_search_graph.py@@ -14,7 +14,6 @@ from ..nodes import ()from ..utils.copy import safe_deepcopy-class OmniSearchGraph(AbstractGraph):"""OmniSearchGraph is a scraping pipeline that searches the internet for answers to a given prompt.diff --git a/scrapegraphai/graphs/screenshot_scraper_graph.py b/scrapegraphai/graphs/screenshot_scraper_graph.pyindex f3ce608d..174e245a 100644--- a/scrapegraphai/graphs/screenshot_scraper_graph.py+++ b/scrapegraphai/graphs/screenshot_scraper_graph.py@@ -47,6 +47,7 @@ class ScreenshotScraperGraph(AbstractGraph):"link": self.source})+generate_answer_from_image_node = GenerateAnswerFromImageNode(input="screenshots",output=["answer"],diff --git a/scrapegraphai/graphs/script_creator_graph.py b/scrapegraphai/graphs/script_creator_graph.pyindex 732fb3cf..f6a884a1 100644--- a/scrapegraphai/graphs/script_creator_graph.py+++ b/scrapegraphai/graphs/script_creator_graph.py@@ -68,6 +68,7 @@ class ScriptCreatorGraph(AbstractGraph):"script_creator": True})+parse_node = ParseNode(input="doc",output=["parsed_doc"],@@ -76,6 +77,7 @@ class ScriptCreatorGraph(AbstractGraph):"llm_model": self.llm_model})+generate_scraper_node = GenerateScraperNode(input="user_prompt & (parsed_doc)",output=["answer"],diff --git a/scrapegraphai/graphs/search_graph.py b/scrapegraphai/graphs/search_graph.pyindex 7b29e051..8086caa6 100644--- a/scrapegraphai/graphs/search_graph.py+++ b/scrapegraphai/graphs/search_graph.py@@ -4,11 +4,9 @@ SearchGraph Modulefrom copy import deepcopyfrom typing import Optional, Listfrom pydantic import BaseModel-from .base_graph import BaseGraphfrom .abstract_graph import AbstractGraphfrom .smart_scraper_graph import SmartScraperGraph-from ..nodes import (SearchInternetNode,GraphIteratorNode,@@ -77,6 +75,7 @@ class SearchGraph(AbstractGraph):"search_engine": self.copy_config.get("search_engine")})+graph_iterator_node = GraphIteratorNode(input="user_prompt & urls",output=["results"],diff --git a/scrapegraphai/graphs/smart_scraper_graph.py b/scrapegraphai/graphs/smart_scraper_graph.pyindex 0c025c3a..e2bda63f 100644--- a/scrapegraphai/graphs/smart_scraper_graph.py+++ b/scrapegraphai/graphs/smart_scraper_graph.py@@ -69,6 +69,7 @@ class SmartScraperGraph(AbstractGraph):"scrape_do": self.config.get("scrape_do")})+parse_node = ParseNode(input="doc",output=["parsed_doc"],diff --git a/scrapegraphai/graphs/smart_scraper_multi_graph.py b/scrapegraphai/graphs/smart_scraper_multi_graph.pyindex 183d8144..5dff3277 100644--- a/scrapegraphai/graphs/smart_scraper_multi_graph.py+++ b/scrapegraphai/graphs/smart_scraper_multi_graph.py@@ -45,9 +45,7 @@ class SmartScraperMultiGraph(AbstractGraph):config: dict, schema: Optional[BaseModel] = None):self.max_results = config.get("max_results", 3)-self.copy_config = safe_deepcopy(config)-self.copy_schema = deepcopy(schema)super().__init__(prompt, config, source, schema)diff --git a/scrapegraphai/graphs/speech_graph.py b/scrapegraphai/graphs/speech_graph.pyindex 6065bcf4..d491d4bc 100644--- a/scrapegraphai/graphs/speech_graph.py+++ b/scrapegraphai/graphs/speech_graph.py@@ -61,6 +61,7 @@ class SpeechGraph(AbstractGraph):input="url | local_dir",output=["doc"])+parse_node = ParseNode(input="doc",output=["parsed_doc"],@@ -69,6 +70,7 @@ class SpeechGraph(AbstractGraph):"llm_model": self.llm_model})+generate_answer_node = GenerateAnswerNode(input="user_prompt & (relevant_chunks | parsed_doc | doc)",output=["answer"],@@ -78,6 +80,7 @@ class SpeechGraph(AbstractGraph):"schema": self.schema})+text_to_speech_node = TextToSpeechNode(input="answer",output=["audio"],diff --git a/scrapegraphai/integrations/burr_bridge.py b/scrapegraphai/integrations/burr_bridge.pyindex 76cce914..959634bb 100644--- a/scrapegraphai/integrations/burr_bridge.py+++ b/scrapegraphai/integrations/burr_bridge.py@@ -15,7 +15,8 @@ try:from burr.core import Application, ApplicationBuilder, State, Action, default, ApplicationContextfrom burr.lifecycle import PostRunStepHook, PreRunStepHookexcept ImportError:- raise ImportError("burr package is not installed. Please install it with 'pip install scrapegraphai[burr]'")+ raise ImportError("""burr package is not installed.+ Please install it with 'pip install scrapegraphai[burr]'""")class PrintLnHook(PostRunStepHook, PreRunStepHook):@@ -32,7 +33,8 @@ class PrintLnHook(PostRunStepHook, PreRunStepHook):class BurrNodeBridge(Action):"""Bridge class to convert a base graph node to a Burr action.- This is nice because we can dynamically declare the inputs/outputs (and not rely on function-parsing).+ This is nice because we can dynamically declare+ the inputs/outputs (and not rely on function-parsing)."""def __init__(self, node):@@ -63,7 +65,8 @@ class BurrNodeBridge(Action):def parse_boolean_expression(expression: str) -> List[str]:"""- Parse a boolean expression to extract the keys used in the expression, without boolean operators.+ Parse a boolean expression to extract the keys+ used in the expression, without boolean operators.Args:expression (str): The boolean expression to parse.@@ -136,10 +139,9 @@ class BurrBridge:if application_context is not None:builder = (builder- # if we're using a tracker, we want to copy it/pass in.with_tracker(application_context.tracker.copy() if application_context.tracker is not None else None- ) # remember to do `copy()` here!+ ).with_spawning_parent(application_context.app_id,application_context.sequence_id,@@ -157,7 +159,8 @@ class BurrBridge:Create Burr actions from the base graph nodes.Returns:- dict: A dictionary of Burr actions with the node name as keys and the action functions as values.+ dict: A dictionary of Burr actions with the node name+ as keys and the action functions as values."""actions = {}diff --git a/scrapegraphai/integrations/indexify_node.py b/scrapegraphai/integrations/indexify_node.pyindex e12adc69..cf15cd0e 100644--- a/scrapegraphai/integrations/indexify_node.py+++ b/scrapegraphai/integrations/indexify_node.py@@ -3,16 +3,9 @@ IndexifyNode Module"""from typing import List, Optional-from ..utils.logging import get_loggerfrom ..nodes.base_node import BaseNode-# try:-# import indexify-# except ImportError:-# raise ImportError("indexify package is not installed. Please install it with 'pip install scrapegraphai[indexify]'")--class IndexifyNode(BaseNode):"""A node responsible for indexing the content present in the state.@@ -61,7 +54,7 @@ class IndexifyNode(BaseNode):# Interpret input keys based on the provided input expression# input_keys length matches the min_input_len parameter in the __init__ method# e.g. "answer & parsed_doc" or "answer | img_urls"-+input_keys = self.get_input_keys(state)# Fetching data from the state based on the input keysdiff --git a/scrapegraphai/nodes/base_node.py b/scrapegraphai/nodes/base_node.pyindex e4dae794..8ba55452 100644--- a/scrapegraphai/nodes/base_node.py+++ b/scrapegraphai/nodes/base_node.py@@ -192,18 +192,14 @@ class BaseNode(ABC):"Invalid operator placement: operators cannot be adjacent.")- # Check for missing or balanced parenthesesif open_parentheses != close_parentheses:raise ValueError("Missing or unbalanced parentheses in expression.")- # Helper function to evaluate an expression without parenthesesdef evaluate_simple_expression(exp: str) -> List[str]:"""Evaluate an expression without parentheses."""- # Split the expression by the OR operator and process each segmentfor or_segment in exp.split("|"):- # Check if all elements in an AND segment are in stateand_segment = or_segment.split("&")if all(elem.strip() in state for elem in and_segment):return [@@ -211,7 +207,6 @@ class BaseNode(ABC):]return []- # Helper function to evaluate expressions with parenthesesdef evaluate_expression(expression: str) -> List[str]:"""Evaluate an expression with parentheses."""@@ -220,10 +215,8 @@ class BaseNode(ABC):end = expression.find(")", start)sub_exp = expression[start + 1 : end]- # Replace the evaluated part with a placeholder and then evaluate itsub_result = evaluate_simple_expression(sub_exp)- # For simplicity in handling, join sub-results with OR to reprocess them laterexpression = (expression[:start] + "|".join(sub_result) + expression[end + 1 :])@@ -236,7 +229,6 @@ class BaseNode(ABC):Expression was {expression}.State contains keys: {', '.join(state.keys())}""")- # Remove redundant state keys from the result, without changing their orderfinal_result = []for key in result:if key not in final_result:diff --git a/scrapegraphai/nodes/concat_answers_node.py b/scrapegraphai/nodes/concat_answers_node.pyindex d9afc356..438218b5 100644--- a/scrapegraphai/nodes/concat_answers_node.py+++ b/scrapegraphai/nodes/concat_answers_node.py@@ -56,19 +56,15 @@ class ConcatAnswersNode(BaseNode):self.logger.info(f"--- Executing {self.node_name} Node ---")- # Interpret input keys based on the provided input expressioninput_keys = self.get_input_keys(state)- # Fetching data from the state based on the input keysinput_data = [state[key] for key in input_keys]answers = input_data[0]-+if len(answers) > 1:- # merge the answers in one stringanswer = self._merge_dict(answers)- # Update the state with the generated answerstate.update({self.output[0]: answer})else:diff --git a/scrapegraphai/nodes/fetch_node.py b/scrapegraphai/nodes/fetch_node.pyindex 053a655b..a548e05b 100644--- a/scrapegraphai/nodes/fetch_node.py+++ b/scrapegraphai/nodes/fetch_node.py@@ -219,7 +219,9 @@ class FetchNode(BaseNode):parsed_content = source- if (isinstance(self.llm_model, ChatOpenAI) or isinstance(self.llm_model, AzureChatOpenAI)) and not self.script_creator or self.force and not self.script_creator:+ if (isinstance(self.llm_model, ChatOpenAI) or \+ isinstance(self.llm_model, AzureChatOpenAI)) \+ and not self.script_creator or self.force and not self.script_creator:parsed_content = convert_to_md(source)else:parsed_content = sourcediff --git a/scrapegraphai/nodes/generate_answer_csv_node.py b/scrapegraphai/nodes/generate_answer_csv_node.pyindex a335381d..0419d891 100644--- a/scrapegraphai/nodes/generate_answer_csv_node.py+++ b/scrapegraphai/nodes/generate_answer_csv_node.py@@ -81,16 +81,13 @@ class GenerateAnswerCSVNode(BaseNode):self.logger.info(f"--- Executing {self.node_name} Node ---")- # Interpret input keys based on the provided input expressioninput_keys = self.get_input_keys(state)- # Fetching data from the state based on the input keysinput_data = [state[key] for key in input_keys]user_prompt = input_data[0]doc = input_data[1]- # Initialize the output parserif self.node_config.get("schema", None) is not None:if isinstance(self.llm_model, (ChatOpenAI, ChatMistralAI)):diff --git a/scrapegraphai/nodes/generate_answer_omni_node.py b/scrapegraphai/nodes/generate_answer_omni_node.pyindex 2824a573..403240dd 100644--- a/scrapegraphai/nodes/generate_answer_omni_node.py+++ b/scrapegraphai/nodes/generate_answer_omni_node.py@@ -81,7 +81,6 @@ class GenerateAnswerOmniNode(BaseNode):doc = input_data[1]imag_desc = input_data[2]- # Initialize the output parserif self.node_config.get("schema", None) is not None:if isinstance(self.llm_model, (ChatOpenAI, ChatMistralAI)):diff --git a/scrapegraphai/nodes/generate_code_node.py b/scrapegraphai/nodes/generate_code_node.pyindex 35de0da0..cc72aaf4 100644--- a/scrapegraphai/nodes/generate_code_node.py+++ b/scrapegraphai/nodes/generate_code_node.py@@ -173,7 +173,9 @@ class GenerateCodeNode(BaseNode):continuebreak- if state["iteration"] == self.max_iterations["overall"] and (state["errors"]["syntax"] or state["errors"]["execution"] or state["errors"]["validation"] or state["errors"]["semantic"]):+ if state["iteration"] == self.max_iterations["overall"] and \+ (state["errors"]["syntax"] or state["errors"]["execution"] \+ or state["errors"]["validation"] or state["errors"]["semantic"]):raise RuntimeError("Max iterations reached without obtaining the desired code.")self.logger.info(f"--- (Code Generated Correctly) ---")@@ -238,7 +240,8 @@ class GenerateCodeNode(BaseNode):def semantic_comparison_loop(self, state: dict) -> dict:for _ in range(self.max_iterations["semantic"]):- comparison_result = self.semantic_comparison(state["execution_result"], state["reference_answer"])+ comparison_result = self.semantic_comparison(state["execution_result"],+ state["reference_answer"])if comparison_result["are_semantically_equivalent"]:state["errors"]["semantic"] = []return statediff --git a/scrapegraphai/nodes/image_to_text_node.py b/scrapegraphai/nodes/image_to_text_node.pyindex 13113aa0..00c71e93 100644--- a/scrapegraphai/nodes/image_to_text_node.py+++ b/scrapegraphai/nodes/image_to_text_node.py@@ -62,10 +62,9 @@ class ImageToTextNode(BaseNode):elif len(urls) == 0:return state.update({self.output[0]: []})- # Skip the image-to-text conversionif self.max_images < 1:return state.update({self.output[0]: []})-+img_desc = []for url in urls[: self.max_images]:try:diff --git a/scrapegraphai/nodes/parse_node.py b/scrapegraphai/nodes/parse_node.pyindex 46e9c1d1..fd2f3810 100644--- a/scrapegraphai/nodes/parse_node.py+++ b/scrapegraphai/nodes/parse_node.py@@ -118,7 +118,7 @@ class ParseNode(BaseNode):"""if not self.parse_urls:return [], []-+image_extensions = default_filters.filter_dict["img_exts"]image_extension_seq = '|'.join(image_extensions).replace('.','')url_pattern = re.compile(r'(https?://[^\s]+|\S+\.(?:' + image_extension_seq + '))')@@ -130,12 +130,12 @@ class ParseNode(BaseNode):all_urls = [url for url in all_urls if url.startswith("http")]else:all_urls = [urljoin(source, url) for url in all_urls]-+images = [url for url in all_urls if any(url.endswith(ext) for ext in image_extensions)]links = [url for url in all_urls if url not in images]return links, images-+def _clean_urls(self, urls: List[str]) -> List[str]:"""Cleans the URLs extracted from the text.@@ -150,7 +150,7 @@ class ParseNode(BaseNode):for url in urls:url = re.sub(r'.*?\]\(', '', url)url = url.rstrip(').')-+cleaned_urls.append(url)-- return cleaned_urls\ No newline at end of file++ return cleaned_urlsdiff --git a/scrapegraphai/nodes/search_link_node.py b/scrapegraphai/nodes/search_link_node.pyindex 935a64ba..10907850 100644--- a/scrapegraphai/nodes/search_link_node.py+++ b/scrapegraphai/nodes/search_link_node.py@@ -13,7 +13,6 @@ from .base_node import BaseNodefrom ..prompts import TEMPLATE_RELEVANT_LINKSfrom ..helpers import default_filters-class SearchLinkNode(BaseNode):"""A node that can filter out the relevant links in the webpage content for the user prompt.diff --git a/scrapegraphai/prompts/generate_answer_node_csv_prompts.py b/scrapegraphai/prompts/generate_answer_node_csv_prompts.pyindex 8df8bde3..b131890e 100644--- a/scrapegraphai/prompts/generate_answer_node_csv_prompts.py+++ b/scrapegraphai/prompts/generate_answer_node_csv_prompts.py@@ -1,6 +1,7 @@"""Generate answer csv schema"""+TEMPLATE_CHUKS_CSV = """You are a scraper and you have just scraped thefollowing content from a csv.diff --git a/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py b/scrapegraphai/prompts/generate_answer_node_pdf_prompts.pyindex a3ea9bef..04472bfa 100644--- a/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py+++ b/scrapegraphai/prompts/generate_answer_node_pdf_prompts.py@@ -1,6 +1,7 @@"""Generate anwer node pdf prompt"""+TEMPLATE_CHUNKS_PDF = """You are a scraper and you have just scraped thefollowing content from a PDF.diff --git a/scrapegraphai/prompts/generate_code_node_prompts.py b/scrapegraphai/prompts/generate_code_node_prompts.pyindex eab92ee4..35d4f786 100644--- a/scrapegraphai/prompts/generate_code_node_prompts.py+++ b/scrapegraphai/prompts/generate_code_node_prompts.py@@ -2,7 +2,6 @@Generate code prompts helper"""-TEMPLATE_INIT_CODE_GENERATION = """**Task**: Create a Python function named `extract_data(html: str) -> dict()` using BeautifulSoup that extracts relevant information from the given HTML code string and returns it in a dictionary matching the Desired JSON Output Schema.diff --git a/scrapegraphai/prompts/html_analyzer_node_prompts.py b/scrapegraphai/prompts/html_analyzer_node_prompts.pyindex d7e6e342..97961047 100644--- a/scrapegraphai/prompts/html_analyzer_node_prompts.py+++ b/scrapegraphai/prompts/html_analyzer_node_prompts.py@@ -2,7 +2,6 @@HTML analysis prompts helper"""-TEMPLATE_HTML_ANALYSIS = """Task: Your job is to analyze the provided HTML code in relation to the initial scraping task analysis and provide all the necessary HTML information useful for implementing a function that extracts data from the given HTML string.diff --git a/scrapegraphai/telemetry/telemetry.py b/scrapegraphai/telemetry/telemetry.pyindex 61af900c..91073e28 100644--- a/scrapegraphai/telemetry/telemetry.py+++ b/scrapegraphai/telemetry/telemetry.py@@ -14,6 +14,7 @@ To disable sending telemetry there are three ways:or:export SCRAPEGRAPHAI_TELEMETRY_ENABLED=false"""+import configparserimport functoolsimport importlib.metadatadiff --git a/scrapegraphai/utils/cleanup_code.py b/scrapegraphai/utils/cleanup_code.pyindex 9bf91e62..ad3d437b 100644--- a/scrapegraphai/utils/cleanup_code.py+++ b/scrapegraphai/utils/cleanup_code.py@@ -5,7 +5,7 @@ import redef extract_code(code: str) -> str:pattern = r'```(?:python)?\n(.*?)```'-+match = re.search(pattern, code, re.DOTALL)-- return match.group(1) if match else code\ No newline at end of file++ return match.group(1) if match else codediff --git a/scrapegraphai/utils/cleanup_html.py b/scrapegraphai/utils/cleanup_html.pyindex 1521fe01..832f811e 100644--- a/scrapegraphai/utils/cleanup_html.py+++ b/scrapegraphai/utils/cleanup_html.py@@ -57,22 +57,17 @@ def cleanup_html(html_content: str, base_url: str) -> str:def minify_html(html):- # Remove comments+ """+ minify_html function+ """html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)-- # Remove whitespace between tags+html = re.sub(r'>\s+<', '><', html)-- # Remove whitespace at the beginning and end of tagshtml = re.sub(r'\s+>', '>', html)html = re.sub(r'<\s+', '<', html)-- # Collapse multiple whitespace characters into a single spacehtml = re.sub(r'\s+', ' ', html)-- # Remove spaces around equals signs in attributeshtml = re.sub(r'\s*=\s*', '=', html)-+return html.strip()def reduce_html(html, reduction):@@ -84,52 +79,45 @@ def reduce_html(html, reduction):reduction (int): The level of reduction to apply to the HTML content.0: minification only,1: minification and removig unnecessary tags and attributes,- 2: minification, removig unnecessary tags and attributes, simplifying text content, removing of the head tag+ 2: minification, removig unnecessary tags and attributes,+ simplifying text content, removing of the head tagReturns:str: The reduced HTML content based on the specified reduction level."""if reduction == 0:return minify_html(html)-+soup = BeautifulSoup(html, 'html.parser')-- # Remove comments+for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):comment.extract()-- # Remove script and style tag contents, but keep the tags+for tag in soup(['script', 'style']):tag.string = ""-- # Remove unnecessary attributes, but keep class and id+attrs_to_keep = ['class', 'id', 'href', 'src']for tag in soup.find_all(True):for attr in list(tag.attrs):if attr not in attrs_to_keep:del tag[attr]-+if reduction == 1:return minify_html(str(soup))-- # Remove script and style tags completely+for tag in soup(['script', 'style']):tag.decompose()-- # Focus only on the body+body = soup.bodyif not body:return "No <body> tag found in the HTML"-- # Simplify text content+for tag in body.find_all(string=True):if tag.parent.name not in ['script', 'style']:tag.replace_with(re.sub(r'\s+', ' ', tag.strip())[:20])-- # Generate reduced HTML+reduced_html = str(body)-- # Apply minification+reduced_html = minify_html(reduced_html)-- return reduced_html\ No newline at end of file++ return reduced_htmldiff --git a/scrapegraphai/utils/code_error_analysis.py b/scrapegraphai/utils/code_error_analysis.pyindex fba7e005..ac955502 100644--- a/scrapegraphai/utils/code_error_analysis.py+++ b/scrapegraphai/utils/code_error_analysis.py@@ -45,4 +45,4 @@ def semantic_focused_analysis(state: dict, comparison_result: Dict[str, Any], ll"generated_code": state["generated_code"],"differences": json.dumps(comparison_result["differences"], indent=2),"explanation": comparison_result["explanation"]- })\ No newline at end of file+ })diff --git a/scrapegraphai/utils/code_error_correction.py b/scrapegraphai/utils/code_error_correction.pyindex 276c7a62..52e92e4c 100644--- a/scrapegraphai/utils/code_error_correction.py+++ b/scrapegraphai/utils/code_error_correction.py@@ -1,9 +1,9 @@"""This module contains the code generation functions for code correction for different types errors."""+import jsonfrom langchain.prompts import PromptTemplatefrom langchain_core.output_parsers import StrOutputParser-import jsonfrom ..prompts import (TEMPLATE_SYNTAX_CODE_GENERATION, TEMPLATE_EXECUTION_CODE_GENERATION,TEMPLATE_VALIDATION_CODE_GENERATION, TEMPLATE_SEMANTIC_CODE_GENERATION@@ -42,4 +42,4 @@ def semantic_focused_code_generation(state: dict, analysis: str, llm_model) -> s"generated_code": state["generated_code"],"generated_result": json.dumps(state["execution_result"], indent=2),"reference_result": json.dumps(state["reference_answer"], indent=2)- })\ No newline at end of file+ })diff --git a/scrapegraphai/utils/llm_callback_manager.py b/scrapegraphai/utils/llm_callback_manager.pyindex 03bdaf0b..86a4de83 100644--- a/scrapegraphai/utils/llm_callback_manager.py+++ b/scrapegraphai/utils/llm_callback_manager.py@@ -1,6 +1,7 @@"""This module provides a custom callback manager for the LLM models."""+import threadingfrom contextlib import contextmanagerfrom langchain_community.callbacks import get_openai_callbackdiff --git a/scrapegraphai/utils/output_parser.py b/scrapegraphai/utils/output_parser.pyindex 3eabfa8b..c3d81e9c 100644--- a/scrapegraphai/utils/output_parser.py+++ b/scrapegraphai/utils/output_parser.py@@ -22,7 +22,9 @@ def get_structured_output_parser(schema: Union[Dict[str, Any],return _dict_output_parser-def get_pydantic_output_parser(schema: Union[Dict[str, Any], Type[BaseModelV1 | BaseModelV2], Type]) -> JsonOutputParser:+def get_pydantic_output_parser(schema: Union[Dict[str, Any],+ Type[BaseModelV1 | BaseModelV2], Type])+-> JsonOutputParser:"""Get the correct output parser for the LLM model.diff --git a/scrapegraphai/utils/prettify_exec_info.py b/scrapegraphai/utils/prettify_exec_info.pyindex 07a36e49..7582bac7 100644--- a/scrapegraphai/utils/prettify_exec_info.py+++ b/scrapegraphai/utils/prettify_exec_info.py@@ -3,7 +3,6 @@ Prettify the execution information of the graph."""import pandas as pd-def prettify_exec_info(complete_result: list[dict]) -> pd.DataFrame:"""Transforms the execution information of a graph into a DataFrame for enhanced visualization.