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 saving functions
VinciGit00587dfa5c6809
diff --git a/README.md b/README.mdindex b250c9fc..16734b93 100644--- a/README.md+++ b/README.md@@ -97,6 +97,7 @@ For more information, please see the [contributing guidelines](https://github.co[](https://discord.gg/DujC7HG8)[](https://www.linkedin.com/company/scrapegraphai/)+[](https://twitter.com/scrapegraph)## ❤️ Contributors[](https://github.com/VinciGit00/Scrapegraph-ai/graphs/contributors)diff --git a/examples/graph_examples/custom_graph_openai.py b/examples/graph_examples/custom_graph_openai.pyindex 6c86ecde..4f982ace 100644--- a/examples/graph_examples/custom_graph_openai.py+++ b/examples/graph_examples/custom_graph_openai.py@@ -7,6 +7,7 @@ from dotenv import load_dotenvfrom scrapegraphai.models import OpenAIfrom scrapegraphai.graphs import BaseGraphfrom scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode+from scrapegraphai.utils import convert_to_csv, convert_to_jsonload_dotenv()openai_key = os.getenv("OPENAI_APIKEY")@@ -68,3 +69,7 @@ result = graph.execute({# get the answer from the resultresult = result.get("answer", "No answer found.")print(result)++# Save to json and csv+convert_to_csv(result, "result")+convert_to_json(result, "result")diff --git a/examples/graph_examples/result.csv b/examples/graph_examples/result.csvnew file mode 100644index 00000000..97ef817e--- /dev/null+++ b/examples/graph_examples/result.csv@@ -0,0 +1,2 @@+0,1,2,3+"{'title': 'Rotary Pendulum RL', 'description': 'Open Source project aimed at controlling a real life rotary pendulum using RL algorithms'}","{'title': 'DQN Implementation from scratch', 'description': 'Developed a Deep Q-Network algorithm to train a simple and double pendulum'}","{'title': 'Multi Agents HAED', 'description': 'University project which focuses on simulating a multi-agent system to perform environment mapping. Agents, equipped with sensors, explore and record their surroundings, considering uncertainties in their readings.'}","{'title': 'Wireless ESC for Modular Drones', 'description': 'Modular drone architecture proposal and proof of concept. The project received maximum grade.'}"diff --git a/examples/graph_examples/result.json b/examples/graph_examples/result.jsonnew file mode 100644index 00000000..8a4e7057--- /dev/null+++ b/examples/graph_examples/result.json@@ -0,0 +1 @@+{"projects": [{"title": "Rotary Pendulum RL", "description": "Open Source project aimed at controlling a real life rotary pendulum using RL algorithms"}, {"title": "DQN Implementation from scratch", "description": "Developed a Deep Q-Network algorithm to train a simple and double pendulum"}, {"title": "Multi Agents HAED", "description": "University project which focuses on simulating a multi-agent system to perform environment mapping. Agents, equipped with sensors, explore and record their surroundings, considering uncertainties in their readings."}, {"title": "Wireless ESC for Modular Drones", "description": "Modular drone architecture proposal and proof of concept. The project received maximum grade."}]}\ No newline at end of filediff --git a/examples/graph_examples/scrape_plain_text.py b/examples/graph_examples/scrape_plain_text.pyindex 04c2dad1..4062ab86 100644--- a/examples/graph_examples/scrape_plain_text.py+++ b/examples/graph_examples/scrape_plain_text.py@@ -30,3 +30,5 @@ smart_scraper_graph = SmartScraperGraph(result = smart_scraper_graph.run()print(result)++# Save to json or csvdiff --git a/examples/graph_examples/smart_scraper_example.py b/examples/graph_examples/smart_scraper_example.pyindex 414e16ab..cc9ba530 100644--- a/examples/graph_examples/smart_scraper_example.py+++ b/examples/graph_examples/smart_scraper_example.py@@ -5,6 +5,7 @@ Basic example of scraping pipeline using SmartScraperimport osfrom dotenv import load_dotenvfrom scrapegraphai.graphs import SmartScraperGraph+from scrapegraphai.utils import convert_to_csv, convert_to_jsonload_dotenv()openai_key = os.getenv("OPENAI_APIKEY")@@ -20,9 +21,14 @@ graph_config = {# Create the SmartScraperGraph instancesmart_scraper_graph = SmartScraperGraph(prompt="List me all the news with their description.",- file_source="https://www.ansa.it/veneto/", # also accepts a local file path+ # also accepts a string with the already downloaded HTML code+ file_source="https://www.wired.com",config=graph_config)result = smart_scraper_graph.run()print(result)++# Save to json and csv+convert_to_csv(result, "result")+convert_to_json(result, "result")diff --git a/examples/graph_examples/speech_graph_example.py b/examples/graph_examples/speech_graph_example.pyindex 7afac269..6c2d9785 100644--- a/examples/graph_examples/speech_graph_example.py+++ b/examples/graph_examples/speech_graph_example.py@@ -5,6 +5,7 @@ Basic example of scraping pipeline using SpeechSummaryGraphimport osfrom dotenv import load_dotenvfrom scrapegraphai.graphs import SpeechGraph+from scrapegraphai.utils import convert_to_csv, convert_to_jsonload_dotenv()openai_key = os.getenv("OPENAI_APIKEY")@@ -36,3 +37,7 @@ speech_graph = SpeechGraph(result = speech_graph.run()print(result.get("answer", "No answer found"))++# Save to json and csv+convert_to_csv(result, "result")+convert_to_json(result, "result")diff --git a/scrapegraphai/utils/convert_to_csv.py b/scrapegraphai/utils/convert_to_csv.pyindex b44f8ef9..982ac45e 100644--- a/scrapegraphai/utils/convert_to_csv.py+++ b/scrapegraphai/utils/convert_to_csv.py@@ -2,30 +2,45 @@Module that given a filename and a position saves the file in the csv format"""import os+import sysimport pandas as pd-def convert_to_csv(data: dict, filename: str, position: str):+def convert_to_csv(data: dict, filename: str, position: str = None):"""- Convert data to JSON format and save it to a file.+ Converts a dictionary to a CSV file and saves it.Args:- data (dict): Data to save.- filename (str): Name of the file to save without .csv extension.- position (str): Directory where the file should be saved.+ data (dict): Data to be converted to CSV.+ filename (str): Name of the CSV file (without the .csv extension).+ position (str): Optional path where the file should be saved. If not provided,+ the directory of the caller script will be used.Raises:- ValueError: If filename contains '.csv'.- FileNotFoundError: If the specified directory does not exist.- PermissionError: If the program does not have permission to write to the directory.+ ValueError: If the filename contains '.csv'.+ FileNotFoundError: If the specified directory does not exist.+ PermissionError: If the program lacks write permission for the directory.+ TypeError: If the input data is not a dictionary.+ Exception: For other potential errors during DataFrame creation or CSV saving."""+if ".csv" in filename:raise ValueError("The filename should not contain '.csv'")+ # Get the directory of the caller script if position is not provided+ if position is None:+ caller_dir = os.path.dirname(os.path.abspath(sys.argv[0]))+ position = caller_dir+try:- os.makedirs(position, exist_ok=True)- pd.DataFrame.from_dict(data, orient='index').to_csv(- os.path.join(position, f"{filename}.csv"), index=False)+ if not isinstance(data, dict):+ raise TypeError("Input data must be a dictionary")++ os.makedirs(position, exist_ok=True) # Create directory if needed++ df = pd.DataFrame.from_dict(data, orient='index')+ df.to_csv(os.path.join(position, f"{filename}.csv"), index=False)+except FileNotFoundError as fnfe:raise FileNotFoundError(f"The specified directory '{position}' does not exist.") from fnfe@@ -33,4 +48,4 @@ def convert_to_csv(data: dict, filename: str, position: str):raise PermissionError(f"You don't have permission to write to '{position}'.") from peexcept Exception as e:- raise e+ raise e # Re-raise other potential errorsdiff --git a/scrapegraphai/utils/convert_to_json.py b/scrapegraphai/utils/convert_to_json.pyindex ead2442d..8ac282cd 100644--- a/scrapegraphai/utils/convert_to_json.py+++ b/scrapegraphai/utils/convert_to_json.py@@ -1,27 +1,35 @@"""-Module that given a filename and a position saves the file in the json format+Convert to json module"""import jsonimport os+import sys-def convert_to_json(data: dict, filename: str, position: str):+def convert_to_json(data: dict, filename: str, position: str = None):"""- Convert data to CSV format and save it to a file.+ Convert data to JSON format and save it to a file.Args:- data (dict): Data to save.- filename (str): Name of the file to save without .json extension.- position (str): Directory where the file should be saved.+ data (dict): Data to save.+ filename (str): Name of the file to save without .json extension.+ position (str): Directory where the file should be saved. If None,+ the directory of the caller script will be used.Raises:- ValueError: If filename contains '.json'.- FileNotFoundError: If the specified directory does not exist.- PermissionError: If the program does not have permission to write to the directory.+ ValueError: If filename contains '.json'.+ FileNotFoundError: If the specified directory does not exist.+ PermissionError: If the program does not have permission to write to the directory."""if ".json" in filename:raise ValueError("The filename should not contain '.json'")+ # Get the directory of the caller script+ if position is None:+ # Get directory of the main script+ caller_dir = os.path.dirname(os.path.abspath(sys.argv[0]))+ position = caller_dir+try:os.makedirs(position, exist_ok=True)with open(os.path.join(position, f"{filename}.json"), "w", encoding="utf-8") as f:@@ -32,5 +40,3 @@ def convert_to_json(data: dict, filename: str, position: str):except PermissionError as pe:raise PermissionError(f"You don't have permission to write to '{position}'.") from pe- except Exception as e:- raise e