Skip to content

Python scraper based on AI

run pre commit

Marco Vinciguerradc0a138a7e5b
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
index 3dbf9273..8868e7e6 100644
--- a/.github/FUNDING.yml
+++ b/.github/FUNDING.yml
@@ -12,4 +12,4 @@ lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cl
polar: # Replace with a single Polar username
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
thanks_dev: # Replace with a single thanks.dev username
-custom:
+custom:
diff --git a/.github/ISSUE_TEMPLATE/custom.md b/.github/ISSUE_TEMPLATE/custom.md
index 48d5f81f..b894315f 100644
--- a/.github/ISSUE_TEMPLATE/custom.md
+++ b/.github/ISSUE_TEMPLATE/custom.md
@@ -6,5 +6,3 @@ labels: ''
assignees: ''
---
-
-
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 0ad43347..125c557c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -19,21 +19,21 @@ jobs:
uses: actions/setup-python@v5
with:
python-version: '3.10'
-
+
- name: Install uv
uses: astral-sh/setup-uv@v3
-
+
- name: Install Node Env
uses: actions/setup-node@v4
with:
node-version: 20
-
+
- name: Checkout
uses: actions/[email protected]
with:
fetch-depth: 0
persist-credentials: false
-
+
- name: Build and validate package
run: |
uv venv
@@ -44,10 +44,10 @@ jobs:
uv build
uv pip install --upgrade pkginfo==1.12.0 twine==6.0.1 # Upgrade pkginfo and install twine
python -m twine check dist/*
-
+
- name: Debug Dist Directory
run: ls -al dist
-
+
- name: Cache build
uses: actions/cache@v3
with:
@@ -59,7 +59,7 @@ jobs:
runs-on: ubuntu-latest
needs: build
environment: development
- if: >
+ if: >
github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/pre/beta') ||
(github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.merged &&
(github.event.pull_request.base.ref == 'main' || github.event.pull_request.base.ref == 'pre/beta'))
@@ -74,23 +74,23 @@ jobs:
with:
fetch-depth: 0
persist-credentials: false
-
+
- name: Restore build artifacts
uses: actions/cache@v3
with:
path: ./dist
key: ${{ runner.os }}-build-${{ github.sha }}
-
+
- name: Semantic Release
uses: cycjimmy/[email protected]
with:
semantic_version: 23
extra_plugins: |
semantic-release-pypi@3
- @semantic-release/git
- @semantic-release/commit-analyzer@12
- @semantic-release/release-notes-generator@13
- @semantic-release/github@10
+ @semantic-release/git
+ @semantic-release/commit-analyzer@12
+ @semantic-release/release-notes-generator@13
+ @semantic-release/github@10
@semantic-release/changelog@6
conventional-changelog-conventionalcommits@7
env:
diff --git a/.releaserc.yml b/.releaserc.yml
index 65d589fa..574eb74e 100644
--- a/.releaserc.yml
+++ b/.releaserc.yml
@@ -53,4 +53,3 @@ branches:
channel: "dev"
prerelease: "beta"
debug: true
-
diff --git a/Dockerfile b/Dockerfile
index a5f71732..d3246bc7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -6,4 +6,4 @@ RUN pip install --no-cache-dir scrapegraphai
RUN pip install --no-cache-dir scrapegraphai[burr]
RUN python3 -m playwright install-deps
-RUN python3 -m playwright install
\ No newline at end of file
+RUN python3 -m playwright install
diff --git a/LICENSE b/LICENSE
index 70e38342..404d6c0c 100644
--- a/LICENSE
+++ b/LICENSE
@@ -4,4 +4,4 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
+THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index df75fbd9..00a169cb 100644
--- a/README.md
+++ b/README.md
@@ -182,7 +182,7 @@ The Official API Documentation can be found [here](https://docs.scrapegraphai.co
</a>
</div>
-## 📈 Telemetry
+## 📈 Telemetry
We collect anonymous usage metrics to enhance our package's quality and user experience. The data helps us prioritize improvements and ensure compatibility. If you wish to opt-out, set the environment variable SCRAPEGRAPHAI_TELEMETRY_ENABLED=false. For more information, please refer to the documentation [here](https://scrapegraph-ai.readthedocs.io/en/latest/scrapers/telemetry.html).
diff --git a/SECURITY.md b/SECURITY.md
index e9de9357..36eb39b9 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -3,4 +3,3 @@
## Reporting a Vulnerability
For reporting a vulnerability contact directly [email protected]
-
diff --git a/docs/README.md b/docs/README.md
index 037f0117..598580fc 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -55,7 +55,7 @@ markmap:
- Use Selenium or Playwright to take screenshots
- Use LLM to asses if it is a block-like page, paragraph-like page, etc.
- [Issue #88](https://github.com/VinciGit00/Scrapegraph-ai/issues/88)
-
+
## **Long-Term Goals**
- Automatic generation of scraping pipelines from a given prompt
diff --git a/docs/russian.md b/docs/russian.md
index 84da9796..ac16ef41 100644
--- a/docs/russian.md
+++ b/docs/russian.md
@@ -228,4 +228,4 @@ ScrapeGraphAI лицензирован под MIT License. Подробнее с
## Благодарности
- Мы хотели бы поблагодарить всех участников проекта и сообщество с открытым исходным кодом за их поддержку.
-- ScrapeGraphAI предназначен только для исследования данных и научных целей. Мы не несем ответственности за неправильное использование библиотеки.
\ No newline at end of file
+- ScrapeGraphAI предназначен только для исследования данных и научных целей. Мы не несем ответственности за неправильное использование библиотеки.
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 9fc3aec7..f7d44113 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -12,31 +12,30 @@ import os
import sys
# import all the modules
-sys.path.insert(0, os.path.abspath('../../'))
+sys.path.insert(0, os.path.abspath("../../"))
-project = 'ScrapeGraphAI'
-copyright = '2024, ScrapeGraphAI'
-author = 'Marco Vinciguerra, Marco Perini, Lorenzo Padoan'
+project = "ScrapeGraphAI"
+copyright = "2024, ScrapeGraphAI"
+author = "Marco Vinciguerra, Marco Perini, Lorenzo Padoan"
html_last_updated_fmt = "%b %d, %Y"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.napoleon']
+extensions = ["sphinx.ext.autodoc", "sphinx.ext.napoleon"]
-templates_path = ['_templates']
+templates_path = ["_templates"]
exclude_patterns = []
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
-html_theme = 'furo'
+html_theme = "furo"
html_theme_options = {
"source_repository": "https://github.com/VinciGit00/Scrapegraph-ai/",
"source_branch": "main",
"source_directory": "docs/source/",
- 'navigation_with_keys': True,
- 'sidebar_hide_name': False,
+ "navigation_with_keys": True,
+ "sidebar_hide_name": False,
}
-
diff --git a/docs/source/getting_started/examples.rst b/docs/source/getting_started/examples.rst
index 1bed0a6e..5696e468 100644
--- a/docs/source/getting_started/examples.rst
+++ b/docs/source/getting_started/examples.rst
@@ -84,4 +84,4 @@ After that, you can run the following code, using only your machine resources br
result = smart_scraper_graph.run()
print(result)
-To find out how you can customize the `graph_config` dictionary, by using different LLM and adding new parameters, check the `Scrapers` section!
\ No newline at end of file
+To find out how you can customize the `graph_config` dictionary, by using different LLM and adding new parameters, check the `Scrapers` section!
diff --git a/docs/source/getting_started/installation.rst b/docs/source/getting_started/installation.rst
index 30acfb5a..a9fd7626 100644
--- a/docs/source/getting_started/installation.rst
+++ b/docs/source/getting_started/installation.rst
@@ -22,7 +22,7 @@ The library is available on PyPI, so it can be installed using the following com
pip install scrapegraphai
.. important::
-
+
It is higly recommended to install the library in a virtual environment (conda, venv, etc.)
If your clone the repository, it is recommended to use a package manager like `uv <https://github.com/astral-sh/uv>`_.
@@ -35,7 +35,7 @@ To install the library using uv, you can run the following command:
uv build
.. caution::
-
+
**Rye** must be installed first by following the instructions on the `official website <https://github.com/astral-sh/uv>`_.
Additionally on Windows when using WSL
@@ -46,5 +46,3 @@ If you are using Windows Subsystem for Linux (WSL) and you are facing issues wit
.. code-block:: bash
sudo apt-get -y install libnss3 libnspr4 libgbm1 libasound2
-
-
diff --git a/docs/source/index.rst b/docs/source/index.rst
index acc0db73..9d0b5a15 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -43,4 +43,4 @@ Indices and tables
* :ref:`genindex`
* :ref:`modindex`
-* :ref:`search`
\ No newline at end of file
+* :ref:`search`
diff --git a/docs/source/introduction/overview.rst b/docs/source/introduction/overview.rst
index 4dcaadbe..e2bdf961 100644
--- a/docs/source/introduction/overview.rst
+++ b/docs/source/introduction/overview.rst
@@ -3,11 +3,11 @@
:width: 50%
:alt: ScrapegraphAI
-Overview
+Overview
========
ScrapeGraphAI is an **open-source** Python library designed to revolutionize **scraping** tools.
-In today's data-intensive digital landscape, this library stands out by integrating **Large Language Models** (LLMs)
+In today's data-intensive digital landscape, this library stands out by integrating **Large Language Models** (LLMs)
and modular **graph-based** pipelines to automate the scraping of data from various sources (e.g., websites, local files etc.).
Simply specify the information you need to extract, and ScrapeGraphAI handles the rest, providing a more **flexible** and **low-maintenance** solution compared to traditional scraping tools.
@@ -16,7 +16,7 @@ Why ScrapegraphAI?
==================
Traditional web scraping tools often rely on fixed patterns or manual configuration to extract data from web pages.
-ScrapegraphAI, leveraging the power of LLMs, adapts to changes in website structures, reducing the need for constant developer intervention.
+ScrapegraphAI, leveraging the power of LLMs, adapts to changes in website structures, reducing the need for constant developer intervention.
This flexibility ensures that scrapers remain functional even when website layouts change.
We support many LLMs including **GPT, Gemini, Groq, Azure, Hugging Face** etc.
@@ -161,13 +161,13 @@ FAQ
- Check your internet connection. Low speed or unstable connection can cause the HTML to not load properly.
- Try using a proxy server to mask your IP address. Check out the :ref:`Proxy` section for more information on how to configure proxy settings.
-
+
- Use a different LLM model. Some models might perform better on certain websites than others.
- Set the `verbose` parameter to `True` in the graph_config to see more detailed logs.
- Visualize the pipeline graphically using :ref:`Burr`.
-
+
If the issue persists, please report it on the GitHub repository.
6. **How does ScrapeGraphAI handle the context window limit of LLMs?**
diff --git a/docs/source/modules/modules.rst b/docs/source/modules/modules.rst
index 7551ea96..d3237dcd 100644
--- a/docs/source/modules/modules.rst
+++ b/docs/source/modules/modules.rst
@@ -7,4 +7,3 @@ scrapegraphai
scrapegraphai
scrapegraphai.helpers.models_tokens
-
diff --git a/docs/source/modules/scrapegraphai.helpers.models_tokens.rst b/docs/source/modules/scrapegraphai.helpers.models_tokens.rst
index 82615b3b..6df4f086 100644
--- a/docs/source/modules/scrapegraphai.helpers.models_tokens.rst
+++ b/docs/source/modules/scrapegraphai.helpers.models_tokens.rst
@@ -25,4 +25,4 @@ Example usage:
else:
print(f"{model_name} not found in the models list")
-This information is crucial for users to understand the capabilities and limitations of different AI models when designing their scraping pipelines.
\ No newline at end of file
+This information is crucial for users to understand the capabilities and limitations of different AI models when designing their scraping pipelines.
diff --git a/docs/source/scrapers/llm.rst b/docs/source/scrapers/llm.rst
index 7b1df30e..bc0ed9bb 100644
--- a/docs/source/scrapers/llm.rst
+++ b/docs/source/scrapers/llm.rst
@@ -133,11 +133,11 @@ We can also pass a model instance for the chat model and the embedding model. Fo
openai_api_version="AZURE_OPENAI_API_VERSION",
)
# Supposing model_tokens are 100K
- model_tokens_count = 100000
+ model_tokens_count = 100000
graph_config = {
"llm": {
"model_instance": llm_model_instance,
- "model_tokens": model_tokens_count,
+ "model_tokens": model_tokens_count,
},
"embeddings": {
"model_instance": embedder_model_instance
@@ -198,7 +198,7 @@ We can also pass a model instance for the chat model and the embedding model. Fo
Other LLM models
^^^^^^^^^^^^^^^^
-We can also pass a model instance for the chat model and the embedding model through the **model_instance** parameter.
+We can also pass a model instance for the chat model and the embedding model through the **model_instance** parameter.
This feature enables you to utilize a Langchain model instance.
You will discover the model you require within the provided list:
@@ -208,7 +208,7 @@ You will discover the model you require within the provided list:
For instance, consider **chat model** Moonshot. We can integrate it in the following manner:
.. code-block:: python
-
+
from langchain_community.chat_models.moonshot import MoonshotChat
# The configuration parameters are contingent upon the specific model you select
@@ -221,8 +221,7 @@ For instance, consider **chat model** Moonshot. We can integrate it in the follo
llm_model_instance = MoonshotChat(**llm_instance_config)
graph_config = {
"llm": {
- "model_instance": llm_model_instance,
+ "model_instance": llm_model_instance,
"model_tokens": 5000
},
}
-
\ No newline at end of file
diff --git a/examples/ScrapegraphAI_cookbook.ipynb b/examples/ScrapegraphAI_cookbook.ipynb
index b58bf0ea..5016c8c7 100644
--- a/examples/ScrapegraphAI_cookbook.ipynb
+++ b/examples/ScrapegraphAI_cookbook.ipynb
@@ -912,4 +912,4 @@
},
"nbformat": 4,
"nbformat_minor": 0
-}
\ No newline at end of file
+}
diff --git a/examples/code_generator_graph/.env.example b/examples/code_generator_graph/.env.example
index a93912e4..93a1b024 100644
--- a/examples/code_generator_graph/.env.example
+++ b/examples/code_generator_graph/.env.example
@@ -11,4 +11,4 @@ DEFAULT_LANGUAGE=python
GENERATE_TESTS=true
ADD_DOCUMENTATION=true
CODE_STYLE=pep8
-TYPE_CHECKING=true
\ No newline at end of file
+TYPE_CHECKING=true
diff --git a/examples/code_generator_graph/README.md b/examples/code_generator_graph/README.md
index bc4b5dec..13d90f5a 100644
--- a/examples/code_generator_graph/README.md
+++ b/examples/code_generator_graph/README.md
@@ -27,4 +27,4 @@ code = graph.generate("code specification")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/code_generator_graph/ollama/code_generator_graph_ollama.py b/examples/code_generator_graph/ollama/code_generator_graph_ollama.py
index 46ab8ab3..339bb03c 100644
--- a/examples/code_generator_graph/ollama/code_generator_graph_ollama.py
+++ b/examples/code_generator_graph/ollama/code_generator_graph_ollama.py
@@ -1,11 +1,13 @@
-"""
+"""
Basic example of scraping pipeline using Code Generator with schema
"""
import json
from typing import List
+
from dotenv import load_dotenv
from pydantic import BaseModel, Field
+
from scrapegraphai.graphs import CodeGeneratorGraph
load_dotenv()
@@ -14,13 +16,16 @@ load_dotenv()
# Define the output schema for the graph
# ************************************************
+
class Project(BaseModel):
title: str = Field(description="The title of the project")
description: str = Field(description="The description of the project")
+
class Projects(BaseModel):
projects: List[Project]
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -41,9 +46,9 @@ graph_config = {
"syntax": 3,
"execution": 3,
"validation": 3,
- "semantic": 3
+ "semantic": 3,
},
- "output_file_name": "extracted_data.py"
+ "output_file_name": "extracted_data.py",
}
# ************************************************
@@ -54,8 +59,8 @@ code_generator_graph = CodeGeneratorGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io/projects/",
schema=Projects,
- config=graph_config
+ config=graph_config,
)
result = code_generator_graph.run()
-print(result)
\ No newline at end of file
+print(result)
diff --git a/examples/code_generator_graph/openai/code_generator_graph_openai.py b/examples/code_generator_graph/openai/code_generator_graph_openai.py
index a9a2ea56..0fe01ebe 100644
--- a/examples/code_generator_graph/openai/code_generator_graph_openai.py
+++ b/examples/code_generator_graph/openai/code_generator_graph_openai.py
@@ -1,10 +1,13 @@
-"""
+"""
Basic example of scraping pipeline using Code Generator with schema
"""
+
import os
from typing import List
+
from dotenv import load_dotenv
from pydantic import BaseModel, Field
+
from scrapegraphai.graphs import CodeGeneratorGraph
load_dotenv()
@@ -13,13 +16,16 @@ load_dotenv()
# Define the output schema for the graph
# ************************************************
+
class Project(BaseModel):
title: str = Field(description="The title of the project")
description: str = Field(description="The description of the project")
+
class Projects(BaseModel):
projects: List[Project]
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -28,7 +34,7 @@ openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
"llm": {
- "api_key":openai_key,
+ "api_key": openai_key,
"model": "openai/gpt-4o-mini",
},
"verbose": True,
@@ -39,9 +45,9 @@ graph_config = {
"syntax": 3,
"execution": 3,
"validation": 3,
- "semantic": 3
+ "semantic": 3,
},
- "output_file_name": "extracted_data.py"
+ "output_file_name": "extracted_data.py",
}
# ************************************************
@@ -52,7 +58,7 @@ code_generator_graph = CodeGeneratorGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io/projects/",
schema=Projects,
- config=graph_config
+ config=graph_config,
)
result = code_generator_graph.run()
diff --git a/examples/csv_scraper_graph/.env.example b/examples/csv_scraper_graph/.env.example
index 1917f9aa..1a7559ea 100644
--- a/examples/csv_scraper_graph/.env.example
+++ b/examples/csv_scraper_graph/.env.example
@@ -8,4 +8,4 @@ TEMPERATURE=0.7
# CSV Scraper Settings
CSV_DELIMITER=,
-MAX_ROWS=1000
\ No newline at end of file
+MAX_ROWS=1000
diff --git a/examples/csv_scraper_graph/README.md b/examples/csv_scraper_graph/README.md
index d39858b0..17a49665 100644
--- a/examples/csv_scraper_graph/README.md
+++ b/examples/csv_scraper_graph/README.md
@@ -27,4 +27,4 @@ csv_data = graph.scrape("https://example.com/table")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/csv_scraper_graph/ollama/inputs/username.csv b/examples/csv_scraper_graph/ollama/inputs/username.csv
index 006ac8e6..0d32afd0 100644
--- a/examples/csv_scraper_graph/ollama/inputs/username.csv
+++ b/examples/csv_scraper_graph/ollama/inputs/username.csv
@@ -4,4 +4,3 @@ grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
-
diff --git a/examples/csv_scraper_graph/openai/inputs/username.csv b/examples/csv_scraper_graph/openai/inputs/username.csv
index 006ac8e6..0d32afd0 100644
--- a/examples/csv_scraper_graph/openai/inputs/username.csv
+++ b/examples/csv_scraper_graph/openai/inputs/username.csv
@@ -4,4 +4,3 @@ grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
-
diff --git a/examples/custom_graph/.env.example b/examples/custom_graph/.env.example
index 9eac4cb8..bb0a8eed 100644
--- a/examples/custom_graph/.env.example
+++ b/examples/custom_graph/.env.example
@@ -10,4 +10,4 @@ TEMPERATURE=0.7
CUSTOM_NODE_TIMEOUT=30
MAX_NODES=10
DEBUG_MODE=false
-LOG_LEVEL=info
\ No newline at end of file
+LOG_LEVEL=info
diff --git a/examples/custom_graph/README.md b/examples/custom_graph/README.md
index e6d3b88a..2b4ffbbf 100644
--- a/examples/custom_graph/README.md
+++ b/examples/custom_graph/README.md
@@ -28,4 +28,4 @@ results = graph.process()
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/custom_graph/ollama/custom_graph_ollama.py b/examples/custom_graph/ollama/custom_graph_ollama.py
index c505d068..f7aebd3d 100644
--- a/examples/custom_graph/ollama/custom_graph_ollama.py
+++ b/examples/custom_graph/ollama/custom_graph_ollama.py
@@ -3,10 +3,17 @@ Example of custom graph using existing nodes
"""
import os
-from langchain_openai import OpenAIEmbeddings
-from langchain_openai import ChatOpenAI
+
+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+
from scrapegraphai.graphs import BaseGraph
-from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode, RobotsNode
+from scrapegraphai.nodes import (
+ FetchNode,
+ GenerateAnswerNode,
+ ParseNode,
+ RAGNode,
+ RobotsNode,
+)
# ************************************************
# Define the configuration for the graph
@@ -20,7 +27,6 @@ graph_config = {
# "model_tokens": 2000, # set context length arbitrarily
"base_url": "http://localhost:11434",
},
-
"verbose": True,
}
@@ -39,7 +45,7 @@ robot_node = RobotsNode(
"llm_model": llm_model,
"force_scraping": True,
"verbose": True,
- }
+ },
)
fetch_node = FetchNode(
@@ -48,7 +54,7 @@ fetch_node = FetchNode(
node_config={
"verbose": True,
"headless": True,
- }
+ },
)
parse_node = ParseNode(
input="doc",
@@ -56,7 +62,7 @@ parse_node = ParseNode(
node_config={
"chunk_size": 4096,
"verbose": True,
- }
+ },
)
generate_answer_node = GenerateAnswerNode(
@@ -65,7 +71,7 @@ generate_answer_node = GenerateAnswerNode(
node_config={
"llm_model": llm_model,
"verbose": True,
- }
+ },
)
# ************************************************
@@ -82,19 +88,18 @@ graph = BaseGraph(
edges=[
(robot_node, fetch_node),
(fetch_node, parse_node),
- (parse_node, generate_answer_node)
+ (parse_node, generate_answer_node),
],
- entry_point=robot_node
+ entry_point=robot_node,
)
# ************************************************
# Execute the graph
# ************************************************
-result, execution_info = graph.execute({
- "user_prompt": "Describe the content",
- "url": "https://example.com/"
-})
+result, execution_info = graph.execute(
+ {"user_prompt": "Describe the content", "url": "https://example.com/"}
+)
# get the answer from the result
result = result.get("answer", "No answer found.")
diff --git a/examples/custom_graph/openai/custom_graph_openai.py b/examples/custom_graph/openai/custom_graph_openai.py
index 00fecfdd..ead1617c 100644
--- a/examples/custom_graph/openai/custom_graph_openai.py
+++ b/examples/custom_graph/openai/custom_graph_openai.py
@@ -1,12 +1,20 @@
"""
Example of custom graph using existing nodes
"""
+
import os
+
from dotenv import load_dotenv
-from langchain_openai import OpenAIEmbeddings
-from langchain_openai import ChatOpenAI
+from langchain_openai import ChatOpenAI, OpenAIEmbeddings
+
from scrapegraphai.graphs import BaseGraph
-from scrapegraphai.nodes import FetchNode, ParseNode, RAGNode, GenerateAnswerNode, RobotsNode
+from scrapegraphai.nodes import (
+ FetchNode,
+ GenerateAnswerNode,
+ ParseNode,
+ RAGNode,
+ RobotsNode,
+)
load_dotenv()
@@ -16,7 +24,7 @@ load_dotenv()
openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
- "llm": {
+ "llm": {
"api_key": openai_key,
"model": "gpt-4o",
},
@@ -37,7 +45,7 @@ robot_node = RobotsNode(
"llm_model": llm_model,
"force_scraping": True,
"verbose": True,
- }
+ },
)
fetch_node = FetchNode(
@@ -46,7 +54,7 @@ fetch_node = FetchNode(
node_config={
"verbose": True,
"headless": True,
- }
+ },
)
parse_node = ParseNode(
input="doc",
@@ -54,7 +62,7 @@ parse_node = ParseNode(
node_config={
"chunk_size": 4096,
"verbose": True,
- }
+ },
)
rag_node = RAGNode(
input="user_prompt & (parsed_doc | doc)",
@@ -63,7 +71,7 @@ rag_node = RAGNode(
"llm_model": llm_model,
"embedder_model": embedder,
"verbose": True,
- }
+ },
)
generate_answer_node = GenerateAnswerNode(
input="user_prompt & (relevant_chunks | parsed_doc | doc)",
@@ -71,7 +79,7 @@ generate_answer_node = GenerateAnswerNode(
node_config={
"llm_model": llm_model,
"verbose": True,
- }
+ },
)
# ************************************************
@@ -90,19 +98,18 @@ graph = BaseGraph(
(robot_node, fetch_node),
(fetch_node, parse_node),
(parse_node, rag_node),
- (rag_node, generate_answer_node)
+ (rag_node, generate_answer_node),
],
- entry_point=robot_node
+ entry_point=robot_node,
)
# ************************************************
# Execute the graph
# ************************************************
-result, execution_info = graph.execute({
- "user_prompt": "Describe the content",
- "url": "https://example.com/"
-})
+result, execution_info = graph.execute(
+ {"user_prompt": "Describe the content", "url": "https://example.com/"}
+)
# get the answer from the result
result = result.get("answer", "No answer found.")
diff --git a/examples/depth_search_graph/.env.example b/examples/depth_search_graph/.env.example
index 8c10cfbb..5498eb26 100644
--- a/examples/depth_search_graph/.env.example
+++ b/examples/depth_search_graph/.env.example
@@ -11,4 +11,4 @@ MAX_DEPTH=5
CRAWL_DELAY=1
RESPECT_ROBOTS_TXT=true
MAX_PAGES_PER_DOMAIN=100
-USER_AGENT=Mozilla/5.0
\ No newline at end of file
+USER_AGENT=Mozilla/5.0
diff --git a/examples/depth_search_graph/README.md b/examples/depth_search_graph/README.md
index c4ce05df..453f21e1 100644
--- a/examples/depth_search_graph/README.md
+++ b/examples/depth_search_graph/README.md
@@ -27,4 +27,4 @@ results = graph.search("https://example.com", depth=3)
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/depth_search_graph/ollama/depth_search_graph_ollama.py b/examples/depth_search_graph/ollama/depth_search_graph_ollama.py
index d0f960b5..c232e2f0 100644
--- a/examples/depth_search_graph/ollama/depth_search_graph_ollama.py
+++ b/examples/depth_search_graph/ollama/depth_search_graph_ollama.py
@@ -1,8 +1,11 @@
"""
depth_search_graph_opeani example
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DepthSearchGraph
load_dotenv()
@@ -25,7 +28,7 @@ graph_config = {
search_graph = DepthSearchGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io",
- config=graph_config
+ config=graph_config,
)
result = search_graph.run()
diff --git a/examples/depth_search_graph/openai/depth_search_graph_openai.py b/examples/depth_search_graph/openai/depth_search_graph_openai.py
index 799d733a..589fc7c7 100644
--- a/examples/depth_search_graph/openai/depth_search_graph_openai.py
+++ b/examples/depth_search_graph/openai/depth_search_graph_openai.py
@@ -1,8 +1,11 @@
"""
depth_search_graph_opeani example
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DepthSearchGraph
load_dotenv()
@@ -23,7 +26,7 @@ graph_config = {
search_graph = DepthSearchGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io",
- config=graph_config
+ config=graph_config,
)
result = search_graph.run()
diff --git a/examples/document_scraper_graph/.env.example b/examples/document_scraper_graph/.env.example
index 2e7bab46..2a1625bb 100644
--- a/examples/document_scraper_graph/.env.example
+++ b/examples/document_scraper_graph/.env.example
@@ -10,4 +10,4 @@ TEMPERATURE=0.7
OCR_ENABLED=true
EXTRACT_METADATA=true
MAX_FILE_SIZE=10485760 # 10MB
-SUPPORTED_FORMATS=pdf,doc,docx,txt
\ No newline at end of file
+SUPPORTED_FORMATS=pdf,doc,docx,txt
diff --git a/examples/document_scraper_graph/README.md b/examples/document_scraper_graph/README.md
index f8561ee7..731ec7fa 100644
--- a/examples/document_scraper_graph/README.md
+++ b/examples/document_scraper_graph/README.md
@@ -27,4 +27,4 @@ content = graph.scrape("document.pdf")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/document_scraper_graph/ollama/document_scraper_ollama.py b/examples/document_scraper_graph/ollama/document_scraper_ollama.py
index 6853a549..12e4a8ea 100644
--- a/examples/document_scraper_graph/ollama/document_scraper_ollama.py
+++ b/examples/document_scraper_graph/ollama/document_scraper_ollama.py
@@ -1,8 +1,11 @@
"""
document_scraper example
"""
+
import json
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DocumentScraperGraph
load_dotenv()
@@ -22,13 +25,13 @@ graph_config = {
}
source = """
- The Divine Comedy, Italian La Divina Commedia, original name La commedia, long narrative poem written in Italian
- circa 1308/21 by Dante. It is usually held to be one of the world s great works of literature.
- Divided into three major sections—Inferno, Purgatorio, and Paradiso—the narrative traces the journey of Dante
- from darkness and error to the revelation of the divine light, culminating in the Beatific Vision of God.
- Dante is guided by the Roman poet Virgil, who represents the epitome of human knowledge, from the dark wood
- through the descending circles of the pit of Hell (Inferno). He then climbs the mountain of Purgatory, guided
- by the Roman poet Statius, who represents the fulfilment of human knowledge, and is finally led by his lifelong love,
+ The Divine Comedy, Italian La Divina Commedia, original name La commedia, long narrative poem written in Italian
+ circa 1308/21 by Dante. It is usually held to be one of the world s great works of literature.
+ Divided into three major sections—Inferno, Purgatorio, and Paradiso—the narrative traces the journey of Dante
+ from darkness and error to the revelation of the divine light, culminating in the Beatific Vision of God.
+ Dante is guided by the Roman poet Virgil, who represents the epitome of human knowledge, from the dark wood
+ through the descending circles of the pit of Hell (Inferno). He then climbs the mountain of Purgatory, guided
+ by the Roman poet Statius, who represents the fulfilment of human knowledge, and is finally led by his lifelong love,
the Beatrice of his earlier poetry, through the celestial spheres of Paradise.
"""
diff --git a/examples/document_scraper_graph/ollama/inputs/plain_html_example.txt b/examples/document_scraper_graph/ollama/inputs/plain_html_example.txt
index 78f814ae..2476565e 100644
--- a/examples/document_scraper_graph/ollama/inputs/plain_html_example.txt
+++ b/examples/document_scraper_graph/ollama/inputs/plain_html_example.txt
@@ -2,16 +2,16 @@
<header>
<nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top">
<div class="container">
- <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
+ <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
<div class="collapse navbar-collapse text-right" id="navbarNav">
<ul class="navbar-nav ml-auto flex-nowrap">
<li class="nav-item "> <a class="nav-link" href="/">About</a> </li>
<li class="nav-item dropdown active">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
+ <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
- <a class="dropdown-item" href="/projects/">Projects</a>
+ <a class="dropdown-item" href="/projects/">Projects</a>
<div class="dropdown-divider"></div>
- <a class="dropdown-item" href="/competitions/">Competitions</a>
+ <a class="dropdown-item" href="/competitions/">Competitions</a>
</div>
</li>
<li class="nav-item "> <a class="nav-link" href="/cv/">CV</a> </li>
@@ -100,6 +100,6 @@
</div>
<footer class="fixed-bottom">
<div class="container mt-0"> © Copyright 2023 Marco Perini. Powered by <a href="https://jekyllrb.com/" target="_blank" rel="external nofollow noopener">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio" rel="external nofollow noopener" target="_blank">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank" rel="external nofollow noopener">GitHub Pages</a>. </div>
- </footer>
+ </footer>
<div class="hiddendiv common"></div>
-</body>
\ No newline at end of file
+</body>
diff --git a/examples/document_scraper_graph/openai/document_scraper_openai.py b/examples/document_scraper_graph/openai/document_scraper_openai.py
index f9475446..ce9f1a2d 100644
--- a/examples/document_scraper_graph/openai/document_scraper_openai.py
+++ b/examples/document_scraper_graph/openai/document_scraper_openai.py
@@ -1,9 +1,12 @@
"""
document_scraper example
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DocumentScraperGraph
load_dotenv()
@@ -19,13 +22,13 @@ graph_config = {
}
source = """
- The Divine Comedy, Italian La Divina Commedia, original name La commedia, long narrative poem written in Italian
- circa 1308/21 by Dante. It is usually held to be one of the world s great works of literature.
- Divided into three major sections—Inferno, Purgatorio, and Paradiso—the narrative traces the journey of Dante
- from darkness and error to the revelation of the divine light, culminating in the Beatific Vision of God.
- Dante is guided by the Roman poet Virgil, who represents the epitome of human knowledge, from the dark wood
- through the descending circles of the pit of Hell (Inferno). He then climbs the mountain of Purgatory, guided
- by the Roman poet Statius, who represents the fulfilment of human knowledge, and is finally led by his lifelong love,
+ The Divine Comedy, Italian La Divina Commedia, original name La commedia, long narrative poem written in Italian
+ circa 1308/21 by Dante. It is usually held to be one of the world s great works of literature.
+ Divided into three major sections—Inferno, Purgatorio, and Paradiso—the narrative traces the journey of Dante
+ from darkness and error to the revelation of the divine light, culminating in the Beatific Vision of God.
+ Dante is guided by the Roman poet Virgil, who represents the epitome of human knowledge, from the dark wood
+ through the descending circles of the pit of Hell (Inferno). He then climbs the mountain of Purgatory, guided
+ by the Roman poet Statius, who represents the fulfilment of human knowledge, and is finally led by his lifelong love,
the Beatrice of his earlier poetry, through the celestial spheres of Paradise.
"""
@@ -36,4 +39,4 @@ pdf_scraper_graph = DocumentScraperGraph(
)
result = pdf_scraper_graph.run()
-print(json.dumps(result, indent=4))
\ No newline at end of file
+print(json.dumps(result, indent=4))
diff --git a/examples/document_scraper_graph/openai/inputs/markdown_example.md b/examples/document_scraper_graph/openai/inputs/markdown_example.md
index 85088f29..d062d5d0 100644
--- a/examples/document_scraper_graph/openai/inputs/markdown_example.md
+++ b/examples/document_scraper_graph/openai/inputs/markdown_example.md
@@ -1,35 +1,35 @@
-Marco Perini Toggle navigation
-
- * About
- * Projects(current)
-
-Projects
-
-Competitions
-
- * CV
- * ____
-
-# Projects
-
- ![project thumbnail Rotary Pendulum RL
-Open Source project aimed at controlling a real life rotary pendulum using RL
-algorithms ](/projects/rotary-pendulum-rl/)
-
- ![project thumbnail DQN
-Implementation from scratch Developed a Deep Q-Network algorithm to train a
-simple and double pendulum ](https://github.com/PeriniM/DQN-SwingUp)
-
- ![project thumbnail Multi Agents HAED
-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.
-](https://github.com/PeriniM/Multi-Agents-HAED)
-
- ![project thumbnail Wireless ESC for Modular
-Drones Modular drone architecture proposal and proof of concept. The project
-received maximum grade. ](/projects/wireless-esc-drone/)
-
-© Copyright 2023 Marco Perini. Powered by Jekyll with
-al-folio theme. Hosted by [GitHub
-Pages](https://pages.github.com/).
\ No newline at end of file
+Marco Perini Toggle navigation
+
+ * About
+ * Projects(current)
+
+Projects
+
+Competitions
+
+ * CV
+ * ____
+
+# Projects
+
+ ![project thumbnail Rotary Pendulum RL
+Open Source project aimed at controlling a real life rotary pendulum using RL
+algorithms ](/projects/rotary-pendulum-rl/)
+
+ ![project thumbnail DQN
+Implementation from scratch Developed a Deep Q-Network algorithm to train a
+simple and double pendulum ](https://github.com/PeriniM/DQN-SwingUp)
+
+ ![project thumbnail Multi Agents HAED
+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.
+](https://github.com/PeriniM/Multi-Agents-HAED)
+
+ ![project thumbnail Wireless ESC for Modular
+Drones Modular drone architecture proposal and proof of concept. The project
+received maximum grade. ](/projects/wireless-esc-drone/)
+
+© Copyright 2023 Marco Perini. Powered by Jekyll with
+al-folio theme. Hosted by [GitHub
+Pages](https://pages.github.com/).
diff --git a/examples/document_scraper_graph/openai/inputs/plain_html_example.txt b/examples/document_scraper_graph/openai/inputs/plain_html_example.txt
index 78f814ae..2476565e 100644
--- a/examples/document_scraper_graph/openai/inputs/plain_html_example.txt
+++ b/examples/document_scraper_graph/openai/inputs/plain_html_example.txt
@@ -2,16 +2,16 @@
<header>
<nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top">
<div class="container">
- <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
+ <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
<div class="collapse navbar-collapse text-right" id="navbarNav">
<ul class="navbar-nav ml-auto flex-nowrap">
<li class="nav-item "> <a class="nav-link" href="/">About</a> </li>
<li class="nav-item dropdown active">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
+ <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
- <a class="dropdown-item" href="/projects/">Projects</a>
+ <a class="dropdown-item" href="/projects/">Projects</a>
<div class="dropdown-divider"></div>
- <a class="dropdown-item" href="/competitions/">Competitions</a>
+ <a class="dropdown-item" href="/competitions/">Competitions</a>
</div>
</li>
<li class="nav-item "> <a class="nav-link" href="/cv/">CV</a> </li>
@@ -100,6 +100,6 @@
</div>
<footer class="fixed-bottom">
<div class="container mt-0"> © Copyright 2023 Marco Perini. Powered by <a href="https://jekyllrb.com/" target="_blank" rel="external nofollow noopener">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio" rel="external nofollow noopener" target="_blank">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank" rel="external nofollow noopener">GitHub Pages</a>. </div>
- </footer>
+ </footer>
<div class="hiddendiv common"></div>
-</body>
\ No newline at end of file
+</body>
diff --git a/examples/extras/.env.example b/examples/extras/.env.example
index dc01444e..618f9d2b 100644
--- a/examples/extras/.env.example
+++ b/examples/extras/.env.example
@@ -1,4 +1,4 @@
OPENAI_API_KEY="YOUR_OPENAI_API_KEY"
BROWSER_BASE_PROJECT_ID="YOUR_BROWSER_BASE_PROJECT_ID"
BROWSER_BASE_API_KEY="YOUR_BROWSERBASE_API_KEY"
-SCRAPE_DO_API_KEY="YOUR_SCRAPE_DO_API_KEY"
\ No newline at end of file
+SCRAPE_DO_API_KEY="YOUR_SCRAPE_DO_API_KEY"
diff --git a/examples/extras/authenticated_playwright.py b/examples/extras/authenticated_playwright.py
index a4926bc7..c5ab4975 100644
--- a/examples/extras/authenticated_playwright.py
+++ b/examples/extras/authenticated_playwright.py
@@ -6,6 +6,7 @@ content.
import os
import random
+
from dotenv import load_dotenv
# import playwright so we can use it to create the state file
diff --git a/examples/extras/browser_base_integration.py b/examples/extras/browser_base_integration.py
index 7030e101..86abc490 100644
--- a/examples/extras/browser_base_integration.py
+++ b/examples/extras/browser_base_integration.py
@@ -1,10 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -35,7 +37,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="List me what does the company do, the name and a contact email.",
source="https://scrapegraphai.com/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/chromium_selenium.py b/examples/extras/chromium_selenium.py
index fba530d4..811ebc2a 100644
--- a/examples/extras/chromium_selenium.py
+++ b/examples/extras/chromium_selenium.py
@@ -1,22 +1,27 @@
import asyncio
-import os
import json
+import os
+
+from aiohttp import ClientError
from dotenv import load_dotenv
-from scrapegraphai.docloaders.chromium import ChromiumLoader # Import your ChromiumLoader class
+
+from scrapegraphai.docloaders.chromium import ( # Import your ChromiumLoader class
+ ChromiumLoader,
+)
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
-from aiohttp import ClientError
# Load environment variables for API keys
load_dotenv()
+
# ************************************************
# Define function to analyze content with ScrapegraphAI
# ************************************************
async def analyze_content_with_scrapegraph(content: str):
"""
Analyze scraped content using ScrapegraphAI.
-
+
Args:
content (str): The scraped HTML or text content.
@@ -33,8 +38,8 @@ async def analyze_content_with_scrapegraph(content: str):
"api_key": os.getenv("OPENAI_API_KEY"),
"model": "openai/gpt-4o",
},
- "verbose": True
- }
+ "verbose": True,
+ },
)
result = smart_scraper.run()
return result
@@ -42,6 +47,7 @@ async def analyze_content_with_scrapegraph(content: str):
print(f"❌ ScrapegraphAI analysis failed: {e}")
return {"error": str(e)}
+
# ************************************************
# Test scraper and ScrapegraphAI pipeline
# ************************************************
@@ -61,7 +67,9 @@ async def test_scraper_with_analysis(scraper: ChromiumLoader, urls: list):
if "Error" in result or not result.strip():
print(f"❌ Failed to scrape {url}: {result}")
else:
- print(f"✅ Successfully scraped {url}. Content (first 200 chars): {result[:200]}")
+ print(
+ f"✅ Successfully scraped {url}. Content (first 200 chars): {result[:200]}"
+ )
# Pass scraped content to ScrapegraphAI for analysis
print("🤖 Analyzing content with ScrapegraphAI...")
@@ -74,6 +82,7 @@ async def test_scraper_with_analysis(scraper: ChromiumLoader, urls: list):
except Exception as e:
print(f"❌ Unexpected error while scraping {url}: {e}")
+
# ************************************************
# Main Execution
# ************************************************
@@ -81,16 +90,26 @@ async def main():
urls_to_scrape = [
"https://example.com",
"https://www.python.org",
- "https://invalid-url.test"
+ "https://invalid-url.test",
]
# Test with Playwright backend
print("\n--- Testing Playwright Backend ---")
try:
- scraper_playwright_chromium = ChromiumLoader(urls=urls_to_scrape, backend="playwright", headless=True, browser_name = "chromium")
+ scraper_playwright_chromium = ChromiumLoader(
+ urls=urls_to_scrape,
+ backend="playwright",
+ headless=True,
+ browser_name="chromium",
+ )
await test_scraper_with_analysis(scraper_playwright_chromium, urls_to_scrape)
-
- scraper_playwright_firefox = ChromiumLoader(urls=urls_to_scrape, backend="playwright", headless=True, browser_name = "firefox")
+
+ scraper_playwright_firefox = ChromiumLoader(
+ urls=urls_to_scrape,
+ backend="playwright",
+ headless=True,
+ browser_name="firefox",
+ )
await test_scraper_with_analysis(scraper_playwright_firefox, urls_to_scrape)
except ImportError as ie:
print(f"❌ Playwright ImportError: {ie}")
@@ -100,16 +119,27 @@ async def main():
# Test with Selenium backend
print("\n--- Testing Selenium Backend ---")
try:
- scraper_selenium_chromium = ChromiumLoader(urls=urls_to_scrape, backend="selenium", headless=True, browser_name = "chromium")
+ scraper_selenium_chromium = ChromiumLoader(
+ urls=urls_to_scrape,
+ backend="selenium",
+ headless=True,
+ browser_name="chromium",
+ )
await test_scraper_with_analysis(scraper_selenium_chromium, urls_to_scrape)
-
- scraper_selenium_firefox = ChromiumLoader(urls=urls_to_scrape, backend="selenium", headless=True, browser_name = "firefox")
+
+ scraper_selenium_firefox = ChromiumLoader(
+ urls=urls_to_scrape,
+ backend="selenium",
+ headless=True,
+ browser_name="firefox",
+ )
await test_scraper_with_analysis(scraper_selenium_firefox, urls_to_scrape)
except ImportError as ie:
print(f"❌ Selenium ImportError: {ie}")
except Exception as e:
print(f"❌ Error initializing Selenium ChromiumLoader: {e}")
+
if __name__ == "__main__":
try:
asyncio.run(main())
diff --git a/examples/extras/cond_smartscraper_usage.py b/examples/extras/cond_smartscraper_usage.py
index 54c40712..5c5e82e9 100644
--- a/examples/extras/cond_smartscraper_usage.py
+++ b/examples/extras/cond_smartscraper_usage.py
@@ -2,9 +2,11 @@
Basic example of scraping pipeline using SmartScraperMultiConcatGraph with Groq
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
load_dotenv()
@@ -20,7 +22,7 @@ graph_config = {
},
"verbose": True,
"headless": True,
- "reattempt": True #Setting this to True will allow the graph to reattempt the scraping process
+ "reattempt": True, # Setting this to True will allow the graph to reattempt the scraping process
}
# *******************************************************
@@ -31,7 +33,7 @@ multiple_search_graph = SmartScraperGraph(
prompt="Who is Marco Perini?",
source="https://perinim.github.io/",
schema=None,
- config=graph_config
+ config=graph_config,
)
result = multiple_search_graph.run()
diff --git a/examples/extras/conditional_usage.py b/examples/extras/conditional_usage.py
index d3152bed..9a136aec 100644
--- a/examples/extras/conditional_usage.py
+++ b/examples/extras/conditional_usage.py
@@ -2,9 +2,11 @@
Basic example of scraping pipeline using SmartScraperMultiConcatGraph with Groq
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperMultiGraph
load_dotenv()
@@ -18,7 +20,6 @@ graph_config = {
"api_key": os.getenv("OPENAI_API_KEY"),
"model": "openai/gpt-4o",
},
-
"verbose": True,
"headless": False,
}
@@ -29,12 +30,9 @@ graph_config = {
multiple_search_graph = SmartScraperMultiGraph(
prompt="Who is Marco Perini?",
- source=[
- "https://perinim.github.io/",
- "https://perinim.github.io/cv/"
- ],
+ source=["https://perinim.github.io/", "https://perinim.github.io/cv/"],
schema=None,
- config=graph_config
+ config=graph_config,
)
result = multiple_search_graph.run()
diff --git a/examples/extras/custom_prompt.py b/examples/extras/custom_prompt.py
index 7def35a3..6d484ce5 100644
--- a/examples/extras/custom_prompt.py
+++ b/examples/extras/custom_prompt.py
@@ -1,9 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
diff --git a/examples/extras/example.yml b/examples/extras/example.yml
index fd5713c7..48bb4f9e 100644
--- a/examples/extras/example.yml
+++ b/examples/extras/example.yml
@@ -3,13 +3,13 @@
"model": "ollama/llama3",
"temperature": 0,
"format": "json",
- # "base_url": "http://localhost:11434",
+ # "base_url": "http://localhost:11434",
},
"embeddings": {
"model": "ollama/nomic-embed-text",
"temperature": 0,
- # "base_url": "http://localhost:11434",
+ # "base_url": "http://localhost:11434",
},
"verbose": true,
"headless": false
-}
\ No newline at end of file
+}
diff --git a/examples/extras/force_mode.py b/examples/extras/force_mode.py
index 85593032..ad3d6475 100644
--- a/examples/extras/force_mode.py
+++ b/examples/extras/force_mode.py
@@ -1,9 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -17,7 +19,7 @@ load_dotenv()
openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
- "llm": {
+ "llm": {
"model": "ollama/llama3",
"temperature": 0,
# "format": "json", # Ollama needs the format to be specified explicitly
@@ -29,7 +31,7 @@ graph_config = {
# "base_url": "http://localhost:11434", # set ollama URL arbitrarily
},
"force": True,
- "caching": True
+ "caching": True,
}
# ************************************************
@@ -40,7 +42,7 @@ smart_scraper_graph = SmartScraperGraph(
prompt="List me all the projects with their description.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/html_mode.py b/examples/extras/html_mode.py
index 6e2670a0..68e2ac6b 100644
--- a/examples/extras/html_mode.py
+++ b/examples/extras/html_mode.py
@@ -1,13 +1,15 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
-By default smart scraper converts in md format the
+By default smart scraper converts in md format the
code. If you want to just use the original code, you have
to specify in the confi
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -35,7 +37,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="List me what does the company do, the name and a contact email.",
source="https://scrapegraphai.com/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/load_yml.py b/examples/extras/load_yml.py
index 974ba4d5..0a3a4857 100644
--- a/examples/extras/load_yml.py
+++ b/examples/extras/load_yml.py
@@ -1,14 +1,16 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
+
import yaml
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
# ************************************************
# Define the configuration for the graph
# ************************************************
-with open("example.yml", 'r') as file:
+with open("example.yml", "r") as file:
graph_config = yaml.safe_load(file)
# ************************************************
@@ -18,7 +20,7 @@ with open("example.yml", 'r') as file:
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the titles",
source="https://sport.sky.it/nba?gr=www",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/no_cut.py b/examples/extras/no_cut.py
index 71bfad86..c638df84 100644
--- a/examples/extras/no_cut.py
+++ b/examples/extras/no_cut.py
@@ -1,12 +1,13 @@
-"""
+"""
This example shows how to do not process the html code in the fetch phase
"""
-import os, json
+import json
+import os
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
-
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -29,7 +30,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="Extract me the python code inside the page",
source="https://www.exploit-db.com/exploits/51447",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/proxy_rotation.py b/examples/extras/proxy_rotation.py
index adfb87ed..c5b3b454 100644
--- a/examples/extras/proxy_rotation.py
+++ b/examples/extras/proxy_rotation.py
@@ -1,11 +1,10 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
-
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -16,12 +15,12 @@ graph_config = {
"model": "openai/gpt-3.5-turbo",
},
"loader_kwargs": {
- "proxy" : {
+ "proxy": {
"server": "http:/**********",
"username": "********",
"password": "***",
},
- },
+ },
"verbose": True,
"headless": False,
}
@@ -34,7 +33,7 @@ smart_scraper_graph = SmartScraperGraph(
prompt="List me all the projects with their description",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/rag_caching.py b/examples/extras/rag_caching.py
index df73d2b4..c3067bc5 100644
--- a/examples/extras/rag_caching.py
+++ b/examples/extras/rag_caching.py
@@ -1,9 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -21,7 +23,7 @@ graph_config = {
"api_key": openai_key,
"model": "openai/gpt-3.5-turbo",
},
- "caching": True
+ "caching": True,
}
# ************************************************
@@ -32,7 +34,7 @@ smart_scraper_graph = SmartScraperGraph(
prompt="List me all the projects with their description.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
@@ -43,4 +45,4 @@ print(result)
# ************************************************
graph_exec_info = smart_scraper_graph.get_execution_info()
-print(prettify_exec_info(graph_exec_info))
\ No newline at end of file
+print(prettify_exec_info(graph_exec_info))
diff --git a/examples/extras/reasoning.py b/examples/extras/reasoning.py
index 80e57faa..46056f8a 100644
--- a/examples/extras/reasoning.py
+++ b/examples/extras/reasoning.py
@@ -1,10 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -32,7 +34,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="List me what does the company do, the name and a contact email.",
source="https://scrapegraphai.com/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/scrape_do.py b/examples/extras/scrape_do.py
index 45026f21..553615b9 100644
--- a/examples/extras/scrape_do.py
+++ b/examples/extras/scrape_do.py
@@ -1,10 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
-import os
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
load_dotenv()
@@ -33,7 +35,7 @@ graph_config = {
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the projects",
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/extras/screenshot_scaping.py b/examples/extras/screenshot_scaping.py
index 439c2a0c..0c5b9e20 100644
--- a/examples/extras/screenshot_scaping.py
+++ b/examples/extras/screenshot_scaping.py
@@ -1,31 +1,38 @@
"""
example of scraping with screenshots
"""
+
import asyncio
-from scrapegraphai.utils.screenshot_scraping import (take_screenshot,
- select_area_with_opencv,
- crop_image, detect_text)
+
+from scrapegraphai.utils.screenshot_scraping import (
+ crop_image,
+ detect_text,
+ select_area_with_opencv,
+ take_screenshot,
+)
# STEP 1: Take a screenshot
-image = asyncio.run(take_screenshot(
- url="https://colab.google/",
- save_path="Savedscreenshots/test_image.jpeg",
- quality = 50
-))
+image = asyncio.run(
+ take_screenshot(
+ url="https://colab.google/",
+ save_path="Savedscreenshots/test_image.jpeg",
+ quality=50,
+ )
+)
# STEP 2 (Optional): Select an area of the image which you want to use for text detection.
LEFT, TOP, RIGHT, BOTTOM = select_area_with_opencv(image)
print("LEFT: ", LEFT, " TOP: ", TOP, " RIGHT: ", RIGHT, " BOTTOM: ", BOTTOM)
# STEP 3 (Optional): Crop the image.
-# Note: If any of the coordinates (LEFT, TOP, RIGHT, BOTTOM) is None,
+# Note: If any of the coordinates (LEFT, TOP, RIGHT, BOTTOM) is None,
# it will be set to the corresponding edge of the image.
-cropped_image = crop_image(image, LEFT=LEFT, RIGHT=RIGHT,TOP=TOP,BOTTOM=BOTTOM)
+cropped_image = crop_image(image, LEFT=LEFT, RIGHT=RIGHT, TOP=TOP, BOTTOM=BOTTOM)
# STEP 4: Detect text
TEXT = detect_text(
- cropped_image, # The image to detect text from
- languages = ["en"] # The languages to detect text in
+ cropped_image, # The image to detect text from
+ languages=["en"], # The languages to detect text in
)
print("DETECTED TEXT: ")
diff --git a/examples/extras/serch_graph_scehma.py b/examples/extras/serch_graph_scehma.py
index 66c47a33..0ad66d4e 100644
--- a/examples/extras/serch_graph_scehma.py
+++ b/examples/extras/serch_graph_scehma.py
@@ -3,28 +3,34 @@ Example of Search Graph
"""
import os
+from typing import List
+
from dotenv import load_dotenv
-from scrapegraphai.graphs import SearchGraph
from pydantic import BaseModel, Field
-from typing import List
+
+from scrapegraphai.graphs import SearchGraph
+
load_dotenv()
+
# ************************************************
# Define the configuration for the graph
# ************************************************
class CeoName(BaseModel):
ceo_name: str = Field(description="The name and surname of the ceo")
+
class Ceos(BaseModel):
names: List[CeoName]
+
openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
"llm": {
"api_key": openai_key,
"model": "openai/gpt-4o",
- },
+ },
"max_results": 2,
"verbose": True,
}
@@ -35,7 +41,7 @@ graph_config = {
search_graph = SearchGraph(
prompt=f"Who is the ceo of Appke?",
- schema = Ceos,
+ schema=Ceos,
config=graph_config,
)
diff --git a/examples/extras/slow_mo.py b/examples/extras/slow_mo.py
index 55b40cd7..c0252eb7 100644
--- a/examples/extras/slow_mo.py
+++ b/examples/extras/slow_mo.py
@@ -1,8 +1,10 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -19,11 +21,9 @@ graph_config = {
"temperature": 0,
# "base_url": "http://localhost:11434", # set ollama URL arbitrarily
},
- "loader_kwargs": {
- "slow_mo": 10000
- },
+ "loader_kwargs": {"slow_mo": 10000},
"verbose": True,
- "headless": False
+ "headless": False,
}
# ************************************************
@@ -34,7 +34,7 @@ smart_scraper_graph = SmartScraperGraph(
prompt="List me all the titles",
# also accepts a string with the already downloaded HTML code
source="https://www.wired.com/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
@@ -45,4 +45,4 @@ print(result)
# ************************************************
graph_exec_info = smart_scraper_graph.get_execution_info()
-print(prettify_exec_info(graph_exec_info))
\ No newline at end of file
+print(prettify_exec_info(graph_exec_info))
diff --git a/examples/extras/undected_playwright.py b/examples/extras/undected_playwright.py
index 999fe42e..65ab1bd8 100644
--- a/examples/extras/undected_playwright.py
+++ b/examples/extras/undected_playwright.py
@@ -1,9 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -16,13 +18,9 @@ load_dotenv()
groq_key = os.getenv("GROQ_APIKEY")
graph_config = {
- "llm": {
- "model": "groq/gemma-7b-it",
- "api_key": groq_key,
- "temperature": 0
- },
+ "llm": {"model": "groq/gemma-7b-it", "api_key": groq_key, "temperature": 0},
"headless": False,
- "backend": "undetected_chromedriver"
+ "backend": "undetected_chromedriver",
}
# ************************************************
@@ -33,7 +31,7 @@ smart_scraper_graph = SmartScraperGraph(
prompt="List me all the projects with their description.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/json_scraper_graph/.env.example b/examples/json_scraper_graph/.env.example
index f1862149..e255cbd6 100644
--- a/examples/json_scraper_graph/.env.example
+++ b/examples/json_scraper_graph/.env.example
@@ -8,4 +8,4 @@ TEMPERATURE=0.7
# JSON Scraper Settings
MAX_DEPTH=3
-TIMEOUT=30
\ No newline at end of file
+TIMEOUT=30
diff --git a/examples/json_scraper_graph/README.md b/examples/json_scraper_graph/README.md
index 217875ff..4c9f8f78 100644
--- a/examples/json_scraper_graph/README.md
+++ b/examples/json_scraper_graph/README.md
@@ -27,4 +27,4 @@ json_data = graph.scrape("https://api.example.com/data")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/json_scraper_graph/ollama/inputs/example.json b/examples/json_scraper_graph/ollama/inputs/example.json
index 2263184c..1cce449a 100644
--- a/examples/json_scraper_graph/ollama/inputs/example.json
+++ b/examples/json_scraper_graph/ollama/inputs/example.json
@@ -179,4 +179,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/examples/json_scraper_graph/ollama/json_scraper_multi_ollama.py b/examples/json_scraper_graph/ollama/json_scraper_multi_ollama.py
index e80bf5ec..9d5238f2 100644
--- a/examples/json_scraper_graph/ollama/json_scraper_multi_ollama.py
+++ b/examples/json_scraper_graph/ollama/json_scraper_multi_ollama.py
@@ -1,8 +1,10 @@
"""
Module for showing how PDFScraper multi works
"""
-import os
+
import json
+import os
+
from scrapegraphai.graphs import JSONScraperMultiGraph
graph_config = {
@@ -20,16 +22,16 @@ FILE_NAME = "inputs/example.json"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
sources = [text, text]
multiple_search_graph = JSONScraperMultiGraph(
- prompt= "List me all the authors, title and genres of the books",
- source= sources,
+ prompt="List me all the authors, title and genres of the books",
+ source=sources,
schema=None,
- config=graph_config
+ config=graph_config,
)
result = multiple_search_graph.run()
diff --git a/examples/json_scraper_graph/ollama/json_scraper_ollama.py b/examples/json_scraper_graph/ollama/json_scraper_ollama.py
index ca4eb32e..157f69a1 100644
--- a/examples/json_scraper_graph/ollama/json_scraper_ollama.py
+++ b/examples/json_scraper_graph/ollama/json_scraper_ollama.py
@@ -3,9 +3,12 @@ Basic example of scraping pipeline using JSONScraperGraph from JSON documents
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import JSONScraperGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
+
load_dotenv()
# ************************************************
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/example.json"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -41,7 +44,7 @@ graph_config = {
json_scraper_graph = JSONScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=text, # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = json_scraper_graph.run()
diff --git a/examples/json_scraper_graph/openai/inputs/example.json b/examples/json_scraper_graph/openai/inputs/example.json
index 2263184c..1cce449a 100644
--- a/examples/json_scraper_graph/openai/inputs/example.json
+++ b/examples/json_scraper_graph/openai/inputs/example.json
@@ -179,4 +179,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/examples/json_scraper_graph/openai/json_scraper_multi_openai.py b/examples/json_scraper_graph/openai/json_scraper_multi_openai.py
index f7cb528a..cd2fb6c0 100644
--- a/examples/json_scraper_graph/openai/json_scraper_multi_openai.py
+++ b/examples/json_scraper_graph/openai/json_scraper_multi_openai.py
@@ -1,9 +1,12 @@
"""
Module for showing how PDFScraper multi works
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import JSONScraperMultiGraph
load_dotenv()
@@ -21,16 +24,16 @@ FILE_NAME = "inputs/example.json"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
sources = [text, text]
multiple_search_graph = JSONScraperMultiGraph(
- prompt= "List me all the authors, title and genres of the books",
- source= sources,
+ prompt="List me all the authors, title and genres of the books",
+ source=sources,
schema=None,
- config=graph_config
+ config=graph_config,
)
result = multiple_search_graph.run()
diff --git a/examples/json_scraper_graph/openai/json_scraper_openai.py b/examples/json_scraper_graph/openai/json_scraper_openai.py
index 891ec32a..4a11a774 100644
--- a/examples/json_scraper_graph/openai/json_scraper_openai.py
+++ b/examples/json_scraper_graph/openai/json_scraper_openai.py
@@ -1,8 +1,11 @@
"""
Basic example of scraping pipeline using JSONScraperGraph from JSON documents
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import JSONScraperGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/example.json"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -39,7 +42,7 @@ graph_config = {
json_scraper_graph = JSONScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=text, # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = json_scraper_graph.run()
diff --git a/examples/json_scraper_graph/openai/md_scraper_openai.py b/examples/json_scraper_graph/openai/md_scraper_openai.py
index 118e7d59..1712b39d 100644
--- a/examples/json_scraper_graph/openai/md_scraper_openai.py
+++ b/examples/json_scraper_graph/openai/md_scraper_openai.py
@@ -1,8 +1,11 @@
"""
Basic example of scraping pipeline using DocumentScraperGraph from MD documents
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DocumentScraperGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/markdown_example.md"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -39,7 +42,7 @@ graph_config = {
md_scraper_graph = DocumentScraperGraph(
prompt="List me all the projects",
source=text, # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = md_scraper_graph.run()
diff --git a/examples/json_scraper_graph/openai/omni_scraper_openai.py b/examples/json_scraper_graph/openai/omni_scraper_openai.py
index 61da3b6a..8fa8aa65 100644
--- a/examples/json_scraper_graph/openai/omni_scraper_openai.py
+++ b/examples/json_scraper_graph/openai/omni_scraper_openai.py
@@ -1,9 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using OmniScraper
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import OmniScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -22,7 +25,7 @@ graph_config = {
},
"verbose": True,
"headless": True,
- "max_images": 5
+ "max_images": 5,
}
# ************************************************
@@ -33,7 +36,7 @@ omni_scraper_graph = OmniScraperGraph(
prompt="List me all the projects with their titles and image links and descriptions.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = omni_scraper_graph.run()
diff --git a/examples/omni_scraper_graph/.env.example b/examples/omni_scraper_graph/.env.example
index d5bb1b4d..d7408ecc 100644
--- a/examples/omni_scraper_graph/.env.example
+++ b/examples/omni_scraper_graph/.env.example
@@ -10,4 +10,4 @@ TEMPERATURE=0.7
DEFAULT_FORMAT=auto
TIMEOUT=60
MAX_RETRIES=3
-USER_AGENT=Mozilla/5.0
\ No newline at end of file
+USER_AGENT=Mozilla/5.0
diff --git a/examples/omni_scraper_graph/README.md b/examples/omni_scraper_graph/README.md
index da5ab652..636713a8 100644
--- a/examples/omni_scraper_graph/README.md
+++ b/examples/omni_scraper_graph/README.md
@@ -27,4 +27,4 @@ data = graph.scrape("https://example.com/data")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/omni_scraper_graph/omni_search_openai.py b/examples/omni_scraper_graph/omni_search_openai.py
index a6fdb266..e8f254d3 100644
--- a/examples/omni_scraper_graph/omni_search_openai.py
+++ b/examples/omni_scraper_graph/omni_search_openai.py
@@ -1,9 +1,12 @@
"""
Example of OmniSearchGraph
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import OmniSearchGraph
from scrapegraphai.utils import prettify_exec_info
@@ -31,7 +34,7 @@ graph_config = {
omni_search_graph = OmniSearchGraph(
prompt="List me all Chioggia's famous dishes and describe their pictures.",
- config=graph_config
+ config=graph_config,
)
result = omni_search_graph.run()
diff --git a/examples/readme.md b/examples/readme.md
index b750ccf8..69adc1ff 100644
--- a/examples/readme.md
+++ b/examples/readme.md
@@ -19,7 +19,7 @@ This directory contains various example implementations of Scrapegraph-ai for di
- 🛠️ `custom_graph/` - Custom graph implementation examples
- 💻 `code_generator_graph/` - Code generation utilities
- 📋 `json_scraper_graph/` - JSON data extraction and processing
-- 📋 `colab example`:
+- 📋 `colab example`:
<a target="_blank" href="https://colab.research.google.com/drive/1sEZBonBMGP44CtO6GQTwAlL0BGJXjtfd?usp=sharing#scrollTo=vGDjka17pqqg">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
diff --git a/examples/script_generator_graph/.env.example b/examples/script_generator_graph/.env.example
index 216ab8a7..3aa7ef65 100644
--- a/examples/script_generator_graph/.env.example
+++ b/examples/script_generator_graph/.env.example
@@ -10,4 +10,4 @@ TEMPERATURE=0.7
DEFAULT_LANGUAGE=python
INCLUDE_COMMENTS=true
ADD_TYPE_HINTS=true
-CODE_STYLE=pep8
\ No newline at end of file
+CODE_STYLE=pep8
diff --git a/examples/script_generator_graph/README.md b/examples/script_generator_graph/README.md
index 7d1495c6..f2381d11 100644
--- a/examples/script_generator_graph/README.md
+++ b/examples/script_generator_graph/README.md
@@ -27,4 +27,4 @@ script = graph.generate("task description")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/script_generator_graph/ollama/script_generator_ollama.py b/examples/script_generator_graph/ollama/script_generator_ollama.py
index caa0455c..8199fdb6 100644
--- a/examples/script_generator_graph/ollama/script_generator_ollama.py
+++ b/examples/script_generator_graph/ollama/script_generator_ollama.py
@@ -1,8 +1,10 @@
"""
Basic example of scraping pipeline using ScriptCreatorGraph
"""
+
from scrapegraphai.graphs import ScriptCreatorGraph
from scrapegraphai.utils import prettify_exec_info
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -26,7 +28,7 @@ smart_scraper_graph = ScriptCreatorGraph(
prompt="List me all the news with their description.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/script_generator_graph/ollama/script_multi_generator_ollama.py b/examples/script_generator_graph/ollama/script_multi_generator_ollama.py
index d94faba6..a8a53f1f 100644
--- a/examples/script_generator_graph/ollama/script_multi_generator_ollama.py
+++ b/examples/script_generator_graph/ollama/script_multi_generator_ollama.py
@@ -1,9 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using ScriptCreatorGraph
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import ScriptCreatorMultiGraph
from scrapegraphai.utils import prettify_exec_info
@@ -28,7 +30,7 @@ graph_config = {
# Create the ScriptCreatorGraph instance and run it
# ************************************************
-urls=[
+urls = [
"https://schultzbergagency.com/emil-raste-karlsen/",
"https://schultzbergagency.com/johanna-hedberg/",
]
@@ -41,7 +43,7 @@ script_creator_graph = ScriptCreatorMultiGraph(
prompt="Find information about actors",
# also accepts a string with the already downloaded HTML code
source=urls,
- config=graph_config
+ config=graph_config,
)
result = script_creator_graph.run()
diff --git a/examples/script_generator_graph/openai/script_generator_multi_openai.py b/examples/script_generator_graph/openai/script_generator_multi_openai.py
index 19eacf66..aab23972 100644
--- a/examples/script_generator_graph/openai/script_generator_multi_openai.py
+++ b/examples/script_generator_graph/openai/script_generator_multi_openai.py
@@ -1,8 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using ScriptCreatorGraph
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import ScriptCreatorMultiGraph
from scrapegraphai.utils import prettify_exec_info
@@ -27,7 +30,7 @@ graph_config = {
# Create the ScriptCreatorGraph instance and run it
# ************************************************
-urls=[
+urls = [
"https://schultzbergagency.com/emil-raste-karlsen/",
"https://schultzbergagency.com/johanna-hedberg/",
]
@@ -40,7 +43,7 @@ script_creator_graph = ScriptCreatorMultiGraph(
prompt="Find information about actors",
# also accepts a string with the already downloaded HTML code
source=urls,
- config=graph_config
+ config=graph_config,
)
result = script_creator_graph.run()
diff --git a/examples/script_generator_graph/openai/script_generator_openai.py b/examples/script_generator_graph/openai/script_generator_openai.py
index 611acc57..e15fb161 100644
--- a/examples/script_generator_graph/openai/script_generator_openai.py
+++ b/examples/script_generator_graph/openai/script_generator_openai.py
@@ -1,9 +1,12 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
-import os
+
import json
+import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import ScriptCreatorGraph
from scrapegraphai.utils import prettify_exec_info
@@ -32,7 +35,7 @@ smart_scraper_graph = ScriptCreatorGraph(
prompt="List me all the news with their description.",
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/examples/script_generator_graph/openai/script_generator_schema_openai.py b/examples/script_generator_graph/openai/script_generator_schema_openai.py
index adb646d1..09f15d2c 100644
--- a/examples/script_generator_graph/openai/script_generator_schema_openai.py
+++ b/examples/script_generator_graph/openai/script_generator_schema_openai.py
@@ -1,10 +1,13 @@
-"""
+"""
Basic example of scraping pipeline using ScriptCreatorGraph
"""
+
import os
from typing import List
+
from dotenv import load_dotenv
from pydantic import BaseModel, Field
+
from scrapegraphai.graphs import ScriptCreatorGraph
from scrapegraphai.utils import prettify_exec_info
@@ -14,13 +17,16 @@ load_dotenv()
# Define the schema for the graph
# ************************************************
+
class Project(BaseModel):
title: str = Field(description="The title of the project")
description: str = Field(description="The description of the project")
+
class Projects(BaseModel):
projects: List[Project]
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -28,10 +34,7 @@ class Projects(BaseModel):
openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
- "llm": {
- "api_key": openai_key,
- "model": "openai/gpt-4o"
- },
+ "llm": {"api_key": openai_key, "model": "openai/gpt-4o"},
"library": "beautifulsoup",
"verbose": True,
}
@@ -45,7 +48,7 @@ script_creator_graph = ScriptCreatorGraph(
# also accepts a string with the already downloaded HTML code
source="https://perinim.github.io/projects",
config=graph_config,
- schema=Projects
+ schema=Projects,
)
result = script_creator_graph.run()
@@ -57,4 +60,3 @@ print(result)
graph_exec_info = script_creator_graph.get_execution_info()
print(prettify_exec_info(graph_exec_info))
-
diff --git a/examples/search_graph/.env.example b/examples/search_graph/.env.example
index a4b25c88..8635bc1e 100644
--- a/examples/search_graph/.env.example
+++ b/examples/search_graph/.env.example
@@ -8,4 +8,4 @@ SERP_API_KEY=your-serp-api-key-here
MAX_SEARCH_RESULTS=10
MAX_TOKENS=4000
MODEL_NAME=gpt-4-1106-preview
-TEMPERATURE=0.7
\ No newline at end of file
+TEMPERATURE=0.7
diff --git a/examples/search_graph/README.md b/examples/search_graph/README.md
index 084c6ea2..fe3319aa 100644
--- a/examples/search_graph/README.md
+++ b/examples/search_graph/README.md
@@ -28,4 +28,4 @@ results = graph.search("your search query")
Required environment variables:
- `OPENAI_API_KEY`: Your OpenAI API key
-- `SERP_API_KEY`: Your SERP API key (optional)
\ No newline at end of file
+- `SERP_API_KEY`: Your SERP API key (optional)
diff --git a/examples/search_graph/ollama/search_graph_ollama.py b/examples/search_graph/ollama/search_graph_ollama.py
index 039ca00e..ecfeba55 100644
--- a/examples/search_graph/ollama/search_graph_ollama.py
+++ b/examples/search_graph/ollama/search_graph_ollama.py
@@ -1,6 +1,7 @@
"""
Example of Search Graph
"""
+
from scrapegraphai.graphs import SearchGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -25,8 +26,7 @@ graph_config = {
# ************************************************
search_graph = SearchGraph(
- prompt="List me the best escursions near Trento",
- config=graph_config
+ prompt="List me the best escursions near Trento", config=graph_config
)
result = search_graph.run()
diff --git a/examples/search_graph/ollama/search_graph_schema_ollama.py b/examples/search_graph/ollama/search_graph_schema_ollama.py
index fb87954f..23c80dc7 100644
--- a/examples/search_graph/ollama/search_graph_schema_ollama.py
+++ b/examples/search_graph/ollama/search_graph_schema_ollama.py
@@ -1,23 +1,28 @@
"""
Example of Search Graph
"""
-from scrapegraphai.graphs import SearchGraph
-from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
-from pydantic import BaseModel, Field
from typing import List
+from pydantic import BaseModel, Field
+
+from scrapegraphai.graphs import SearchGraph
+from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
+
# ************************************************
# Define the output schema for the graph
# ************************************************
+
class Dish(BaseModel):
name: str = Field(description="The name of the dish")
description: str = Field(description="The description of the dish")
+
class Dishes(BaseModel):
dishes: List[Dish]
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -30,7 +35,7 @@ graph_config = {
# "base_url": "http://localhost:11434", # set ollama URL arbitrarily
},
"verbose": True,
- "headless": False
+ "headless": False,
}
# ************************************************
@@ -38,9 +43,7 @@ graph_config = {
# ************************************************
search_graph = SearchGraph(
- prompt="List me Chioggia's famous dishes",
- config=graph_config,
- schema=Dishes
+ prompt="List me Chioggia's famous dishes", config=graph_config, schema=Dishes
)
result = search_graph.run()
diff --git a/examples/search_graph/openai/search_graph_openai.py b/examples/search_graph/openai/search_graph_openai.py
index 5005bd5b..30d742f2 100644
--- a/examples/search_graph/openai/search_graph_openai.py
+++ b/examples/search_graph/openai/search_graph_openai.py
@@ -1,8 +1,11 @@
"""
Example of Search Graph
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SearchGraph
load_dotenv()
@@ -27,8 +30,7 @@ graph_config = {
# ************************************************
search_graph = SearchGraph(
- prompt="List me Chioggia's famous dishes",
- config=graph_config
+ prompt="List me Chioggia's famous dishes", config=graph_config
)
result = search_graph.run()
diff --git a/examples/search_graph/openai/search_graph_schema_openai.py b/examples/search_graph/openai/search_graph_schema_openai.py
index 3109cc79..27e8a1be 100644
--- a/examples/search_graph/openai/search_graph_schema_openai.py
+++ b/examples/search_graph/openai/search_graph_schema_openai.py
@@ -1,10 +1,13 @@
"""
Example of Search Graph
"""
+
import os
from typing import List
+
from dotenv import load_dotenv
from pydantic import BaseModel, Field
+
from scrapegraphai.graphs import SearchGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -14,13 +17,16 @@ load_dotenv()
# Define the output schema for the graph
# ************************************************
+
class Dish(BaseModel):
name: str = Field(description="The name of the dish")
description: str = Field(description="The description of the dish")
+
class Dishes(BaseModel):
dishes: List[Dish]
+
# ************************************************
# Define the configuration for the graph
# ************************************************
@@ -28,10 +34,7 @@ class Dishes(BaseModel):
openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
- "llm": {
- "api_key": openai_key,
- "model": "openai/gpt-4o"
- },
+ "llm": {"api_key": openai_key, "model": "openai/gpt-4o"},
"max_results": 2,
"verbose": True,
}
@@ -41,9 +44,7 @@ graph_config = {
# ************************************************
search_graph = SearchGraph(
- prompt="List me Chioggia's famous dishes",
- config=graph_config,
- schema=Dishes
+ prompt="List me Chioggia's famous dishes", config=graph_config, schema=Dishes
)
result = search_graph.run()
diff --git a/examples/search_graph/openai/search_link_graph_openai.py b/examples/search_graph/openai/search_link_graph_openai.py
index f7436159..6b528255 100644
--- a/examples/search_graph/openai/search_link_graph_openai.py
+++ b/examples/search_graph/openai/search_link_graph_openai.py
@@ -1,8 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using SmartScraper
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SearchLinkGraph
from scrapegraphai.utils import prettify_exec_info
@@ -27,8 +30,7 @@ graph_config = {
# ************************************************
smart_scraper_graph = SearchLinkGraph(
- source="https://sport.sky.it/nba?gr=www",
- config=graph_config
+ source="https://sport.sky.it/nba?gr=www", config=graph_config
)
result = smart_scraper_graph.run()
diff --git a/examples/speech_graph/.env.example b/examples/speech_graph/.env.example
index 93aa505d..4e4c3380 100644
--- a/examples/speech_graph/.env.example
+++ b/examples/speech_graph/.env.example
@@ -11,4 +11,4 @@ TEMPERATURE=0.7
# Speech Settings
AUDIO_FORMAT=mp3
-SAMPLE_RATE=16000
\ No newline at end of file
+SAMPLE_RATE=16000
diff --git a/examples/speech_graph/README.md b/examples/speech_graph/README.md
index 35be155f..91c2c71f 100644
--- a/examples/speech_graph/README.md
+++ b/examples/speech_graph/README.md
@@ -28,4 +28,4 @@ text = graph.process("audio_file.mp3")
Required environment variables:
- `OPENAI_API_KEY`: Your OpenAI API key
-- `WHISPER_API_KEY`: Your Whisper API key (optional)
\ No newline at end of file
+- `WHISPER_API_KEY`: Your Whisper API key (optional)
diff --git a/examples/speech_graph/speech_graph_openai.py b/examples/speech_graph/speech_graph_openai.py
index 8cf32527..fdbaac83 100644
--- a/examples/speech_graph/speech_graph_openai.py
+++ b/examples/speech_graph/speech_graph_openai.py
@@ -1,8 +1,11 @@
-"""
+"""
Basic example of scraping pipeline using SpeechSummaryGraph
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SpeechGraph
from scrapegraphai.utils import prettify_exec_info
@@ -28,11 +31,7 @@ graph_config = {
"model": "openai/gpt-4o",
"temperature": 0.7,
},
- "tts_model": {
- "api_key": openai_key,
- "model": "tts-1",
- "voice": "alloy"
- },
+ "tts_model": {"api_key": openai_key, "model": "tts-1", "voice": "alloy"},
"output_path": output_path,
}
diff --git a/examples/xml_scraper_graph/.env.example b/examples/xml_scraper_graph/.env.example
index 9f0d484b..baf79847 100644
--- a/examples/xml_scraper_graph/.env.example
+++ b/examples/xml_scraper_graph/.env.example
@@ -8,4 +8,4 @@ TEMPERATURE=0.7
# XML Scraper Settings
XPATH_TIMEOUT=30
-VALIDATE_XML=true
\ No newline at end of file
+VALIDATE_XML=true
diff --git a/examples/xml_scraper_graph/README.md b/examples/xml_scraper_graph/README.md
index ed7eaf30..dfdb9cb7 100644
--- a/examples/xml_scraper_graph/README.md
+++ b/examples/xml_scraper_graph/README.md
@@ -27,4 +27,4 @@ xml_data = graph.scrape("https://example.com/feed.xml")
## Environment Variables
Required environment variables:
-- `OPENAI_API_KEY`: Your OpenAI API key
\ No newline at end of file
+- `OPENAI_API_KEY`: Your OpenAI API key
diff --git a/examples/xml_scraper_graph/ollama/inputs/books.xml b/examples/xml_scraper_graph/ollama/inputs/books.xml
index e3d1fe87..df9948ac 100644
--- a/examples/xml_scraper_graph/ollama/inputs/books.xml
+++ b/examples/xml_scraper_graph/ollama/inputs/books.xml
@@ -6,7 +6,7 @@
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
- <description>An in-depth look at creating applications
+ <description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
@@ -15,8 +15,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
- <description>A former architect battles corporate zombies,
- an evil sorceress, and her own childhood to become queen
+ <description>A former architect battles corporate zombies,
+ an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
@@ -25,8 +25,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
- <description>After the collapse of a nanotechnology
- society in England, the young survivors lay the
+ <description>After the collapse of a nanotechnology
+ society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
@@ -35,9 +35,9 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
- <description>In post-apocalypse England, the mysterious
- agent known only as Oberon helps to create a new life
- for the inhabitants of London. Sequel to Maeve
+ <description>In post-apocalypse England, the mysterious
+ agent known only as Oberon helps to create a new life
+ for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
@@ -46,8 +46,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
- <description>The two daughters of Maeve, half-sisters,
- battle one another for control of England. Sequel to
+ <description>The two daughters of Maeve, half-sisters,
+ battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
@@ -56,7 +56,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
- <description>When Carla meets Paul at an ornithology
+ <description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
@@ -65,7 +65,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
- <description>A deep sea diver finds true love twenty
+ <description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
@@ -84,7 +84,7 @@
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
- Uncertainty Device, James Salway discovers the problems
+ Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
@@ -93,7 +93,7 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
- <description>Microsoft's .NET initiative is explored in
+ <description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
@@ -102,8 +102,8 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
- <description>The Microsoft MSXML3 parser is covered in
- detail, with attention to XML DOM interfaces, XSLT processing,
+ <description>The Microsoft MSXML3 parser is covered in
+ detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
@@ -113,8 +113,8 @@
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
- looking at how Visual Basic, Visual C++, C#, and ASP+ are
- integrated into a comprehensive development
+ looking at how Visual Basic, Visual C++, C#, and ASP+ are
+ integrated into a comprehensive development
environment.</description>
</book>
-</catalog>
\ No newline at end of file
+</catalog>
diff --git a/examples/xml_scraper_graph/ollama/xml_scraper_graph_multi_ollama.py b/examples/xml_scraper_graph/ollama/xml_scraper_graph_multi_ollama.py
index 0494ff2c..e3368f1f 100644
--- a/examples/xml_scraper_graph/ollama/xml_scraper_graph_multi_ollama.py
+++ b/examples/xml_scraper_graph/ollama/xml_scraper_graph_multi_ollama.py
@@ -3,6 +3,7 @@ Basic example of scraping pipeline using XMLScraperMultiGraph from XML documents
"""
import os
+
from scrapegraphai.graphs import XMLScraperMultiGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -14,7 +15,7 @@ FILE_NAME = "inputs/books.xml"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -29,7 +30,6 @@ graph_config = {
# "model_tokens": 2000, # set context length arbitrarily
"base_url": "http://localhost:11434",
},
-
"verbose": True,
}
@@ -40,7 +40,7 @@ graph_config = {
xml_scraper_graph = XMLScraperMultiGraph(
prompt="List me all the authors, title and genres of the books",
source=[text, text], # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
diff --git a/examples/xml_scraper_graph/ollama/xml_scraper_ollama.py b/examples/xml_scraper_graph/ollama/xml_scraper_ollama.py
index 50c4f8e7..4b403c67 100644
--- a/examples/xml_scraper_graph/ollama/xml_scraper_ollama.py
+++ b/examples/xml_scraper_graph/ollama/xml_scraper_ollama.py
@@ -3,9 +3,12 @@ Basic example of scraping pipeline using XMLScraperGraph from XML documents
"""
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import XMLScraperGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
+
load_dotenv()
# ************************************************
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/books.xml"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -40,7 +43,7 @@ graph_config = {
xml_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=text, # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
diff --git a/examples/xml_scraper_graph/openai/inputs/books.xml b/examples/xml_scraper_graph/openai/inputs/books.xml
index e3d1fe87..df9948ac 100644
--- a/examples/xml_scraper_graph/openai/inputs/books.xml
+++ b/examples/xml_scraper_graph/openai/inputs/books.xml
@@ -6,7 +6,7 @@
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
- <description>An in-depth look at creating applications
+ <description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
@@ -15,8 +15,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
- <description>A former architect battles corporate zombies,
- an evil sorceress, and her own childhood to become queen
+ <description>A former architect battles corporate zombies,
+ an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
@@ -25,8 +25,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
- <description>After the collapse of a nanotechnology
- society in England, the young survivors lay the
+ <description>After the collapse of a nanotechnology
+ society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
@@ -35,9 +35,9 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
- <description>In post-apocalypse England, the mysterious
- agent known only as Oberon helps to create a new life
- for the inhabitants of London. Sequel to Maeve
+ <description>In post-apocalypse England, the mysterious
+ agent known only as Oberon helps to create a new life
+ for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
@@ -46,8 +46,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
- <description>The two daughters of Maeve, half-sisters,
- battle one another for control of England. Sequel to
+ <description>The two daughters of Maeve, half-sisters,
+ battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
@@ -56,7 +56,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
- <description>When Carla meets Paul at an ornithology
+ <description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
@@ -65,7 +65,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
- <description>A deep sea diver finds true love twenty
+ <description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
@@ -84,7 +84,7 @@
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
- Uncertainty Device, James Salway discovers the problems
+ Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
@@ -93,7 +93,7 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
- <description>Microsoft's .NET initiative is explored in
+ <description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
@@ -102,8 +102,8 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
- <description>The Microsoft MSXML3 parser is covered in
- detail, with attention to XML DOM interfaces, XSLT processing,
+ <description>The Microsoft MSXML3 parser is covered in
+ detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
@@ -113,8 +113,8 @@
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
- looking at how Visual Basic, Visual C++, C#, and ASP+ are
- integrated into a comprehensive development
+ looking at how Visual Basic, Visual C++, C#, and ASP+ are
+ integrated into a comprehensive development
environment.</description>
</book>
-</catalog>
\ No newline at end of file
+</catalog>
diff --git a/examples/xml_scraper_graph/openai/xml_scraper_graph_multi_openai.py b/examples/xml_scraper_graph/openai/xml_scraper_graph_multi_openai.py
index 3604489b..fccaa4b3 100644
--- a/examples/xml_scraper_graph/openai/xml_scraper_graph_multi_openai.py
+++ b/examples/xml_scraper_graph/openai/xml_scraper_graph_multi_openai.py
@@ -1,8 +1,11 @@
"""
Basic example of scraping pipeline using XMLScraperMultiGraph from XML documents
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import XMLScraperMultiGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/books.xml"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -27,7 +30,7 @@ openai_key = os.getenv("OPENAI_APIKEY")
graph_config = {
"llm": {
- "api_key":openai_key,
+ "api_key": openai_key,
"model": "openai/gpt-4o",
},
"verbose": True,
@@ -40,7 +43,7 @@ graph_config = {
xml_scraper_graph = XMLScraperMultiGraph(
prompt="List me all the authors, title and genres of the books",
source=[text, text], # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
diff --git a/examples/xml_scraper_graph/openai/xml_scraper_openai.py b/examples/xml_scraper_graph/openai/xml_scraper_openai.py
index bac87ff9..de6405aa 100644
--- a/examples/xml_scraper_graph/openai/xml_scraper_openai.py
+++ b/examples/xml_scraper_graph/openai/xml_scraper_openai.py
@@ -1,8 +1,11 @@
"""
Basic example of scraping pipeline using XMLScraperGraph from XML documents
"""
+
import os
+
from dotenv import load_dotenv
+
from scrapegraphai.graphs import XMLScraperGraph
from scrapegraphai.utils import prettify_exec_info
@@ -16,7 +19,7 @@ FILE_NAME = "inputs/books.xml"
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
-with open(file_path, 'r', encoding="utf-8") as file:
+with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
# ************************************************
@@ -30,7 +33,7 @@ graph_config = {
"api_key": openai_key,
"model": "openai/gpt-4o",
},
- "verbose":False,
+ "verbose": False,
}
# ************************************************
@@ -40,7 +43,7 @@ graph_config = {
xml_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=text, # Pass the content of the file, not the file object
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
@@ -52,4 +55,3 @@ print(result)
graph_exec_info = xml_scraper_graph.get_execution_info()
print(prettify_exec_info(graph_exec_info))
-
diff --git a/scrapegraphai/utils/research_web.py b/scrapegraphai/utils/research_web.py
index 673319b2..8b2f0cd0 100644
--- a/scrapegraphai/utils/research_web.py
+++ b/scrapegraphai/utils/research_web.py
@@ -23,7 +23,7 @@ def search_on_web(
language: str = None,
) -> List[str]:
"""Search web function with improved error handling and validation
-
+
Args:
query (str): Search query
search_engine (str): Search engine to use
@@ -57,25 +57,34 @@ def search_on_web(
if region and language:
results = list(
google_search(
- query, num_results=max_results, proxy=formatted_proxy,
- lang= language, region=region)
+ query,
+ num_results=max_results,
+ proxy=formatted_proxy,
+ lang=language,
+ region=region,
+ )
)
elif region:
results = list(
google_search(
- query, num_results=max_results, proxy=formatted_proxy,
- region=region)
+ query,
+ num_results=max_results,
+ proxy=formatted_proxy,
+ region=region,
+ )
)
elif language:
results = list(
google_search(
- query, num_results=max_results, proxy=formatted_proxy,
- lang=language)
+ query,
+ num_results=max_results,
+ proxy=formatted_proxy,
+ lang=language,
+ )
)
else:
results = list(
- google_search(
- query, num_results=max_results, proxy=formatted_proxy)
+ google_search(query, num_results=max_results, proxy=formatted_proxy)
)
elif search_engine == "duckduckgo":
diff --git a/tests/Readme.md b/tests/Readme.md
index 747e88e4..561c8b62 100644
--- a/tests/Readme.md
+++ b/tests/Readme.md
@@ -1,4 +1,4 @@
-# Test section
+# Test section
Regarding the tests for the folder graphs and nodes it was created a specific repo as a example
([link of the repo](https://github.com/VinciGit00/Scrapegrah-ai-website-for-tests)). The test website is hosted [here](https://scrapegrah-ai-website-for-tests.onrender.com).
@@ -7,4 +7,4 @@ Remember to activating Ollama and having installed the LLM on your pc
For running the tests run the command:
```python
pytest
-```
\ No newline at end of file
+```
diff --git a/tests/graphs/.env.example b/tests/graphs/.env.example
index 1212e633..d87b814d 100644
--- a/tests/graphs/.env.example
+++ b/tests/graphs/.env.example
@@ -1,2 +1,2 @@
OPENAI_API_KEY="YOUR OPENAI API KEY"
-FIREWORKS_APIKEY="YOOUR FIREWORK KEY"
\ No newline at end of file
+FIREWORKS_APIKEY="YOOUR FIREWORK KEY"
diff --git a/tests/graphs/abstract_graph_test.py b/tests/graphs/abstract_graph_test.py
index 8df4e24e..c17ef09a 100644
--- a/tests/graphs/abstract_graph_test.py
+++ b/tests/graphs/abstract_graph_test.py
@@ -1,18 +1,17 @@
"""
Tests for the AbstractGraph.
"""
-import pytest
+
from unittest.mock import patch
-from scrapegraphai.graphs import AbstractGraph, BaseGraph
-from scrapegraphai.nodes import (
- FetchNode,
- ParseNode
-)
-from scrapegraphai.models import OneApi, DeepSeek
-from langchain_openai import ChatOpenAI, AzureChatOpenAI
-from langchain_ollama import ChatOllama
+
+import pytest
from langchain_aws import ChatBedrock
+from langchain_ollama import ChatOllama
+from langchain_openai import AzureChatOpenAI, ChatOpenAI
+from scrapegraphai.graphs import AbstractGraph, BaseGraph
+from scrapegraphai.models import DeepSeek, OneApi
+from scrapegraphai.nodes import FetchNode, ParseNode
class TestGraph(AbstractGraph):
@@ -28,27 +27,21 @@ class TestGraph(AbstractGraph):
"force": self.config.get("force", False),
"cut": self.config.get("cut", True),
"loader_kwargs": self.config.get("loader_kwargs", {}),
- "browser_base": self.config.get("browser_base")
- }
+ "browser_base": self.config.get("browser_base"),
+ },
)
parse_node = ParseNode(
input="doc",
output=["parsed_doc"],
- node_config={
- "llm_model": self.llm_model,
- "chunk_size": self.model_token
- }
+ node_config={"llm_model": self.llm_model, "chunk_size": self.model_token},
)
return BaseGraph(
- nodes=[
- fetch_node,
- parse_node
- ],
+ nodes=[fetch_node, parse_node],
edges=[
(fetch_node, parse_node),
],
entry_point=fetch_node,
- graph_name=self.__class__.__name__
+ graph_name=self.__class__.__name__,
)
def run(self) -> str:
@@ -59,20 +52,37 @@ class TestGraph(AbstractGraph):
class TestAbstractGraph:
- @pytest.mark.parametrize("llm_config, expected_model", [
- ({"model": "openai/gpt-3.5-turbo", "openai_api_key": "sk-randomtest001"}, ChatOpenAI),
- ({
- "model": "azure_openai/gpt-3.5-turbo",
- "api_key": "random-api-key",
- "api_version": "no version",
- "azure_endpoint": "https://www.example.com/"},
- AzureChatOpenAI),
- ({"model": "ollama/llama2"}, ChatOllama),
- ({"model": "oneapi/qwen-turbo", "api_key": "oneapi-api-key"}, OneApi),
- ({"model": "deepseek/deepseek-coder", "api_key": "deepseek-api-key"}, DeepSeek),
- ({"model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0", "region_name": "IDK"}, ChatBedrock),
- ])
-
+ @pytest.mark.parametrize(
+ "llm_config, expected_model",
+ [
+ (
+ {"model": "openai/gpt-3.5-turbo", "openai_api_key": "sk-randomtest001"},
+ ChatOpenAI,
+ ),
+ (
+ {
+ "model": "azure_openai/gpt-3.5-turbo",
+ "api_key": "random-api-key",
+ "api_version": "no version",
+ "azure_endpoint": "https://www.example.com/",
+ },
+ AzureChatOpenAI,
+ ),
+ ({"model": "ollama/llama2"}, ChatOllama),
+ ({"model": "oneapi/qwen-turbo", "api_key": "oneapi-api-key"}, OneApi),
+ (
+ {"model": "deepseek/deepseek-coder", "api_key": "deepseek-api-key"},
+ DeepSeek,
+ ),
+ (
+ {
+ "model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
+ "region_name": "IDK",
+ },
+ ChatBedrock,
+ ),
+ ],
+ )
def test_create_llm(self, llm_config, expected_model):
graph = TestGraph("Test prompt", {"llm": llm_config})
assert isinstance(graph.llm_model, expected_model)
@@ -81,24 +91,73 @@ class TestAbstractGraph:
with pytest.raises(ValueError):
TestGraph("Test prompt", {"llm": {"model": "unknown_provider/model"}})
- @pytest.mark.parametrize("llm_config, expected_model", [
- ({"model": "openai/gpt-3.5-turbo", "openai_api_key": "sk-randomtest001", "rate_limit": {"requests_per_second": 1}}, ChatOpenAI),
- ({"model": "azure_openai/gpt-3.5-turbo", "api_key": "random-api-key", "api_version": "no version", "azure_endpoint": "https://www.example.com/", "rate_limit": {"requests_per_second": 1}}, AzureChatOpenAI),
- ({"model": "ollama/llama2", "rate_limit": {"requests_per_second": 1}}, ChatOllama),
- ({"model": "oneapi/qwen-turbo", "api_key": "oneapi-api-key", "rate_limit": {"requests_per_second": 1}}, OneApi),
- ({"model": "deepseek/deepseek-coder", "api_key": "deepseek-api-key", "rate_limit": {"requests_per_second": 1}}, DeepSeek),
- ({"model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0", "region_name": "IDK", "rate_limit": {"requests_per_second": 1}}, ChatBedrock),
- ])
-
-
+ @pytest.mark.parametrize(
+ "llm_config, expected_model",
+ [
+ (
+ {
+ "model": "openai/gpt-3.5-turbo",
+ "openai_api_key": "sk-randomtest001",
+ "rate_limit": {"requests_per_second": 1},
+ },
+ ChatOpenAI,
+ ),
+ (
+ {
+ "model": "azure_openai/gpt-3.5-turbo",
+ "api_key": "random-api-key",
+ "api_version": "no version",
+ "azure_endpoint": "https://www.example.com/",
+ "rate_limit": {"requests_per_second": 1},
+ },
+ AzureChatOpenAI,
+ ),
+ (
+ {"model": "ollama/llama2", "rate_limit": {"requests_per_second": 1}},
+ ChatOllama,
+ ),
+ (
+ {
+ "model": "oneapi/qwen-turbo",
+ "api_key": "oneapi-api-key",
+ "rate_limit": {"requests_per_second": 1},
+ },
+ OneApi,
+ ),
+ (
+ {
+ "model": "deepseek/deepseek-coder",
+ "api_key": "deepseek-api-key",
+ "rate_limit": {"requests_per_second": 1},
+ },
+ DeepSeek,
+ ),
+ (
+ {
+ "model": "bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
+ "region_name": "IDK",
+ "rate_limit": {"requests_per_second": 1},
+ },
+ ChatBedrock,
+ ),
+ ],
+ )
def test_create_llm_with_rate_limit(self, llm_config, expected_model):
graph = TestGraph("Test prompt", {"llm": llm_config})
assert isinstance(graph.llm_model, expected_model)
-
+
@pytest.mark.asyncio
async def test_run_safe_async(self):
- graph = TestGraph("Test prompt", {"llm": {"model": "openai/gpt-3.5-turbo", "openai_api_key": "sk-randomtest001"}})
- with patch.object(graph, 'run', return_value="Async result") as mock_run:
+ graph = TestGraph(
+ "Test prompt",
+ {
+ "llm": {
+ "model": "openai/gpt-3.5-turbo",
+ "openai_api_key": "sk-randomtest001",
+ }
+ },
+ )
+ with patch.object(graph, "run", return_value="Async result") as mock_run:
result = await graph.run_safe_async()
assert result == "Async result"
- mock_run.assert_called_once()
\ No newline at end of file
+ mock_run.assert_called_once()
diff --git a/tests/graphs/code_generator_graph_openai_test.py b/tests/graphs/code_generator_graph_openai_test.py
index aa78b672..332fb5ff 100644
--- a/tests/graphs/code_generator_graph_openai_test.py
+++ b/tests/graphs/code_generator_graph_openai_test.py
@@ -1,11 +1,14 @@
"""
code_generator_graph_openai_test module
"""
+
import os
from typing import List
+
import pytest
from dotenv import load_dotenv
from pydantic import BaseModel, Field
+
from scrapegraphai.graphs import CodeGeneratorGraph
load_dotenv()
@@ -14,13 +17,16 @@ load_dotenv()
# Define the output schema for the graph
# ************************************************
+
class Project(BaseModel):
title: str = Field(description="The title of the project")
description: str = Field(description="The description of the project")
+
class Projects(BaseModel):
projects: List[Project]
+
@pytest.fixture
def graph_config():
"""
@@ -40,11 +46,12 @@ def graph_config():
"syntax": 3,
"execution": 3,
"validation": 3,
- "semantic": 3
+ "semantic": 3,
},
- "output_file_name": "extracted_data.py"
+ "output_file_name": "extracted_data.py",
}
+
def test_code_generator_graph(graph_config: dict):
"""
Test the CodeGeneratorGraph scraping pipeline
@@ -53,7 +60,7 @@ def test_code_generator_graph(graph_config: dict):
prompt="List me all the projects with their description",
source="https://perinim.github.io/projects/",
schema=Projects,
- config=graph_config
+ config=graph_config,
)
result = code_generator_graph.run()
@@ -69,7 +76,7 @@ def test_code_generator_execution_info(graph_config: dict):
prompt="List me all the projects with their description",
source="https://perinim.github.io/projects/",
schema=Projects,
- config=graph_config
+ config=graph_config,
)
code_generator_graph.run()
diff --git a/tests/graphs/depth_search_graph_openai_test.py b/tests/graphs/depth_search_graph_openai_test.py
index e53bccdf..d62c0491 100644
--- a/tests/graphs/depth_search_graph_openai_test.py
+++ b/tests/graphs/depth_search_graph_openai_test.py
@@ -1,13 +1,17 @@
"""
depth_search_graph test
"""
+
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import DepthSearchGraph
load_dotenv()
+
@pytest.fixture
def graph_config():
"""
@@ -25,6 +29,7 @@ def graph_config():
"only_inside_links": False,
}
+
def test_depth_search_graph(graph_config: dict):
"""
Test the DepthSearchGraph scraping pipeline
@@ -32,7 +37,7 @@ def test_depth_search_graph(graph_config: dict):
search_graph = DepthSearchGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io",
- config=graph_config
+ config=graph_config,
)
result = search_graph.run()
@@ -47,7 +52,7 @@ def test_depth_search_execution_info(graph_config: dict):
search_graph = DepthSearchGraph(
prompt="List me all the projects with their description",
source="https://perinim.github.io",
- config=graph_config
+ config=graph_config,
)
search_graph.run()
diff --git a/tests/graphs/inputs/books.xml b/tests/graphs/inputs/books.xml
index e3d1fe87..df9948ac 100644
--- a/tests/graphs/inputs/books.xml
+++ b/tests/graphs/inputs/books.xml
@@ -6,7 +6,7 @@
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
- <description>An in-depth look at creating applications
+ <description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
@@ -15,8 +15,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
- <description>A former architect battles corporate zombies,
- an evil sorceress, and her own childhood to become queen
+ <description>A former architect battles corporate zombies,
+ an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
@@ -25,8 +25,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
- <description>After the collapse of a nanotechnology
- society in England, the young survivors lay the
+ <description>After the collapse of a nanotechnology
+ society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
@@ -35,9 +35,9 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
- <description>In post-apocalypse England, the mysterious
- agent known only as Oberon helps to create a new life
- for the inhabitants of London. Sequel to Maeve
+ <description>In post-apocalypse England, the mysterious
+ agent known only as Oberon helps to create a new life
+ for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
@@ -46,8 +46,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
- <description>The two daughters of Maeve, half-sisters,
- battle one another for control of England. Sequel to
+ <description>The two daughters of Maeve, half-sisters,
+ battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
@@ -56,7 +56,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
- <description>When Carla meets Paul at an ornithology
+ <description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
@@ -65,7 +65,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
- <description>A deep sea diver finds true love twenty
+ <description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
@@ -84,7 +84,7 @@
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
- Uncertainty Device, James Salway discovers the problems
+ Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
@@ -93,7 +93,7 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
- <description>Microsoft's .NET initiative is explored in
+ <description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
@@ -102,8 +102,8 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
- <description>The Microsoft MSXML3 parser is covered in
- detail, with attention to XML DOM interfaces, XSLT processing,
+ <description>The Microsoft MSXML3 parser is covered in
+ detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
@@ -113,8 +113,8 @@
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
- looking at how Visual Basic, Visual C++, C#, and ASP+ are
- integrated into a comprehensive development
+ looking at how Visual Basic, Visual C++, C#, and ASP+ are
+ integrated into a comprehensive development
environment.</description>
</book>
-</catalog>
\ No newline at end of file
+</catalog>
diff --git a/tests/graphs/inputs/example.json b/tests/graphs/inputs/example.json
index 2263184c..1cce449a 100644
--- a/tests/graphs/inputs/example.json
+++ b/tests/graphs/inputs/example.json
@@ -179,4 +179,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/tests/graphs/inputs/plain_html_example.txt b/tests/graphs/inputs/plain_html_example.txt
index 78f814ae..2476565e 100644
--- a/tests/graphs/inputs/plain_html_example.txt
+++ b/tests/graphs/inputs/plain_html_example.txt
@@ -2,16 +2,16 @@
<header>
<nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top">
<div class="container">
- <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
+ <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
<div class="collapse navbar-collapse text-right" id="navbarNav">
<ul class="navbar-nav ml-auto flex-nowrap">
<li class="nav-item "> <a class="nav-link" href="/">About</a> </li>
<li class="nav-item dropdown active">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
+ <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
- <a class="dropdown-item" href="/projects/">Projects</a>
+ <a class="dropdown-item" href="/projects/">Projects</a>
<div class="dropdown-divider"></div>
- <a class="dropdown-item" href="/competitions/">Competitions</a>
+ <a class="dropdown-item" href="/competitions/">Competitions</a>
</div>
</li>
<li class="nav-item "> <a class="nav-link" href="/cv/">CV</a> </li>
@@ -100,6 +100,6 @@
</div>
<footer class="fixed-bottom">
<div class="container mt-0"> © Copyright 2023 Marco Perini. Powered by <a href="https://jekyllrb.com/" target="_blank" rel="external nofollow noopener">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio" rel="external nofollow noopener" target="_blank">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank" rel="external nofollow noopener">GitHub Pages</a>. </div>
- </footer>
+ </footer>
<div class="hiddendiv common"></div>
-</body>
\ No newline at end of file
+</body>
diff --git a/tests/graphs/inputs/username.csv b/tests/graphs/inputs/username.csv
index 006ac8e6..0d32afd0 100644
--- a/tests/graphs/inputs/username.csv
+++ b/tests/graphs/inputs/username.csv
@@ -4,4 +4,3 @@ grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
-
diff --git a/tests/graphs/scrape_graph_test.py b/tests/graphs/scrape_graph_test.py
index c79cccca..272fc238 100644
--- a/tests/graphs/scrape_graph_test.py
+++ b/tests/graphs/scrape_graph_test.py
@@ -3,12 +3,15 @@ Module for testing the scrape graph class
"""
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import ScrapeGraph
load_dotenv()
+
@pytest.fixture
def graph_config():
"""Configuration of the graph"""
@@ -22,6 +25,7 @@ def graph_config():
"headless": False,
}
+
def test_scraping_pipeline(graph_config):
"""Start of the scraping pipeline"""
scrape_graph = ScrapeGraph(
@@ -34,6 +38,7 @@ def test_scraping_pipeline(graph_config):
assert result is not None
assert isinstance(result, list)
+
def test_get_execution_info(graph_config):
"""Get the execution info"""
scrape_graph = ScrapeGraph(
diff --git a/tests/graphs/scrape_plain_text_mistral_test.py b/tests/graphs/scrape_plain_text_mistral_test.py
index 888999ab..2a345061 100644
--- a/tests/graphs/scrape_plain_text_mistral_test.py
+++ b/tests/graphs/scrape_plain_text_mistral_test.py
@@ -1,10 +1,14 @@
"""
Module for the tests
"""
+
import os
+
import pytest
+
from scrapegraphai.graphs import SmartScraperGraph
+
@pytest.fixture
def sample_text():
"""
@@ -14,11 +18,12 @@ def sample_text():
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, file_name)
- with open(file_path, 'r', encoding="utf-8") as file:
+ with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
return text
+
@pytest.fixture
def graph_config():
"""
@@ -33,6 +38,7 @@ def graph_config():
}
}
+
def test_scraping_pipeline(sample_text, graph_config):
"""
Test the SmartScraperGraph scraping pipeline.
@@ -40,7 +46,7 @@ def test_scraping_pipeline(sample_text, graph_config):
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
source=sample_text,
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/tests/graphs/scrape_xml_ollama_test.py b/tests/graphs/scrape_xml_ollama_test.py
index 2bc38a59..c9c6250f 100644
--- a/tests/graphs/scrape_xml_ollama_test.py
+++ b/tests/graphs/scrape_xml_ollama_test.py
@@ -1,8 +1,11 @@
-"""
+"""
Module for scraping XML documents
"""
+
import os
+
import pytest
+
from scrapegraphai.graphs import XMLScraperGraph
@@ -15,7 +18,7 @@ def sample_xml():
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, file_name)
- with open(file_path, 'r', encoding="utf-8") as file:
+ with open(file_path, "r", encoding="utf-8") as file:
text = file.read()
return text
@@ -43,7 +46,7 @@ def test_scraping_pipeline(sample_xml: str, graph_config: dict):
smart_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=sample_xml,
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/tests/graphs/screenshot_scraper_test.py b/tests/graphs/screenshot_scraper_test.py
index c4f436d2..ea577dd9 100644
--- a/tests/graphs/screenshot_scraper_test.py
+++ b/tests/graphs/screenshot_scraper_test.py
@@ -1,12 +1,15 @@
+import json
import os
+
import pytest
-import json
-from scrapegraphai.graphs import ScreenshotScraperGraph
from dotenv import load_dotenv
+from scrapegraphai.graphs import ScreenshotScraperGraph
+
# Load environment variables
load_dotenv()
+
# Define a fixture for the graph configuration
@pytest.fixture
def graph_config():
@@ -22,6 +25,7 @@ def graph_config():
"headless": False,
}
+
def test_screenshot_scraper_graph(graph_config):
"""
test
@@ -29,7 +33,7 @@ def test_screenshot_scraper_graph(graph_config):
smart_scraper_graph = ScreenshotScraperGraph(
prompt="List me all the projects",
source="https://perinim.github.io/projects/",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
diff --git a/tests/graphs/script_generator_test.py b/tests/graphs/script_generator_test.py
index 7bcfeea7..d90d2df0 100644
--- a/tests/graphs/script_generator_test.py
+++ b/tests/graphs/script_generator_test.py
@@ -1,34 +1,40 @@
"""
Module for making the tests for ScriptGeneratorGraph
"""
+
import pytest
+
from scrapegraphai.graphs import ScriptCreatorGraph
from scrapegraphai.utils import prettify_exec_info
+
@pytest.fixture
def graph_config():
- """
- Configuration of the graph
- """
- return {
- "llm": {
- "model": "ollama/mistral",
- "temperature": 0,
- "format": "json",
- "base_url": "http://localhost:11434",
- "library": "beautifulsoup",
- },
- "library": "beautifulsoup"
- }
+ """
+ Configuration of the graph
+ """
+ return {
+ "llm": {
+ "model": "ollama/mistral",
+ "temperature": 0,
+ "format": "json",
+ "base_url": "http://localhost:11434",
+ "library": "beautifulsoup",
+ },
+ "library": "beautifulsoup",
+ }
+
def test_script_creator_graph(graph_config: dict):
- """
- Test the ScriptCreatorGraph
- """
- smart_scraper_graph = ScriptCreatorGraph(
- prompt="List me all the news with their description.",
- source="https://perinim.github.io/projects",
- config=graph_config
- )
- result = smart_scraper_graph.run()
- assert result is not None, "ScriptCreatorGraph execution failed to produce a result."
+ """
+ Test the ScriptCreatorGraph
+ """
+ smart_scraper_graph = ScriptCreatorGraph(
+ prompt="List me all the news with their description.",
+ source="https://perinim.github.io/projects",
+ config=graph_config,
+ )
+ result = smart_scraper_graph.run()
+ assert (
+ result is not None
+ ), "ScriptCreatorGraph execution failed to produce a result."
diff --git a/tests/graphs/search_graph_openai_test.py b/tests/graphs/search_graph_openai_test.py
index afdaaa18..c59c0d62 100644
--- a/tests/graphs/search_graph_openai_test.py
+++ b/tests/graphs/search_graph_openai_test.py
@@ -1,9 +1,12 @@
"""
search_graph_openai_test.py module
"""
+
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SearchGraph
load_dotenv()
@@ -12,6 +15,7 @@ load_dotenv()
# Define the test fixtures and helpers
# ************************************************
+
@pytest.fixture
def graph_config():
"""
@@ -27,17 +31,18 @@ def graph_config():
"verbose": True,
}
+
# ************************************************
# Define the test cases
# ************************************************
+
def test_search_graph(graph_config: dict):
"""
Test the SearchGraph functionality
"""
search_graph = SearchGraph(
- prompt="List me Chioggia's famous dishes",
- config=graph_config
+ prompt="List me Chioggia's famous dishes", config=graph_config
)
result = search_graph.run()
@@ -51,8 +56,7 @@ def test_search_graph_execution_info(graph_config: dict):
Test getting the execution info of SearchGraph
"""
search_graph = SearchGraph(
- prompt="List me Chioggia's famous dishes",
- config=graph_config
+ prompt="List me Chioggia's famous dishes", config=graph_config
)
search_graph.run()
diff --git a/tests/graphs/search_link_ollama.py b/tests/graphs/search_link_ollama.py
index 530ad2a6..9801b2fa 100644
--- a/tests/graphs/search_link_ollama.py
+++ b/tests/graphs/search_link_ollama.py
@@ -1,6 +1,7 @@
from scrapegraphai.graphs import SearchLinkGraph
from scrapegraphai.utils import prettify_exec_info
+
def test_smart_scraper_pipeline():
graph_config = {
"llm": {
@@ -9,12 +10,11 @@ def test_smart_scraper_pipeline():
"format": "json",
},
"verbose": True,
- "headless": False
+ "headless": False,
}
smart_scraper_graph = SearchLinkGraph(
- source="https://sport.sky.it/nba?gr=www",
- config=graph_config
+ source="https://sport.sky.it/nba?gr=www", config=graph_config
)
result = smart_scraper_graph.run()
diff --git a/tests/graphs/smart_scraper_ernie_test.py b/tests/graphs/smart_scraper_ernie_test.py
index 7d9e4f26..a16f646b 100644
--- a/tests/graphs/smart_scraper_ernie_test.py
+++ b/tests/graphs/smart_scraper_ernie_test.py
@@ -1,7 +1,9 @@
-"""
+"""
Module for testing th smart scraper class
"""
+
import pytest
+
from scrapegraphai.graphs import SmartScraperGraph
@@ -15,7 +17,7 @@ def graph_config():
"model": "ernie-bot-turbo",
"ernie_client_id": "<ernie_client_id>",
"ernie_client_secret": "<ernie_client_secret>",
- "temperature": 0.1
+ "temperature": 0.1,
}
}
@@ -27,7 +29,7 @@ def test_scraping_pipeline(graph_config: dict):
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
@@ -42,7 +44,7 @@ def test_get_execution_info(graph_config: dict):
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
smart_scraper_graph.run()
diff --git a/tests/graphs/smart_scraper_fireworks_test.py b/tests/graphs/smart_scraper_fireworks_test.py
index cfa5e908..e1372cf9 100644
--- a/tests/graphs/smart_scraper_fireworks_test.py
+++ b/tests/graphs/smart_scraper_fireworks_test.py
@@ -3,25 +3,29 @@ Module for testing the smart scraper class
"""
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
load_dotenv()
+
@pytest.fixture
def graph_config():
"""Configuration of the graph"""
- fireworks_api_key = os.getenv("FIREWORKS_APIKEY")
+ fireworks_api_key = os.getenv("FIREWORKS_APIKEY")
return {
"llm": {
"api_key": fireworks_api_key,
- "model": "fireworks/accounts/fireworks/models/mixtral-8x7b-instruct"
+ "model": "fireworks/accounts/fireworks/models/mixtral-8x7b-instruct",
},
"verbose": True,
"headless": False,
}
+
def test_scraping_pipeline(graph_config):
"""Start of the scraping pipeline"""
smart_scraper_graph = SmartScraperGraph(
@@ -33,7 +37,8 @@ def test_scraping_pipeline(graph_config):
result = smart_scraper_graph.run()
assert result is not None
- assert isinstance(result, dict)
+ assert isinstance(result, dict)
+
def test_get_execution_info(graph_config):
"""Get the execution info"""
diff --git a/tests/graphs/smart_scraper_multi_lite_graph_openai_test.py b/tests/graphs/smart_scraper_multi_lite_graph_openai_test.py
index 7e5b88de..e92b3239 100644
--- a/tests/graphs/smart_scraper_multi_lite_graph_openai_test.py
+++ b/tests/graphs/smart_scraper_multi_lite_graph_openai_test.py
@@ -3,12 +3,15 @@ Module for testing the smart scraper class
"""
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperMultiLiteGraph
load_dotenv()
+
@pytest.fixture
def graph_config():
"""Configuration of the graph"""
@@ -23,30 +26,26 @@ def graph_config():
"headless": False,
}
+
def test_scraping_pipeline(graph_config):
"""Start of the scraping pipeline"""
smart_scraper_multi_lite_graph = SmartScraperMultiLiteGraph(
prompt="Who is Marco Perini?",
- source= [
- "https://perinim.github.io/",
- "https://perinim.github.io/cv/"
- ],
+ source=["https://perinim.github.io/", "https://perinim.github.io/cv/"],
config=graph_config,
)
result = smart_scraper_multi_lite_graph.run()
assert result is not None
- assert isinstance(result, dict)
+ assert isinstance(result, dict)
+
def test_get_execution_info(graph_config):
"""Get the execution info"""
smart_scraper_multi_lite_graph = SmartScraperMultiLiteGraph(
prompt="Who is Marco Perini?",
- source= [
- "https://perinim.github.io/",
- "https://perinim.github.io/cv/"
- ],
+ source=["https://perinim.github.io/", "https://perinim.github.io/cv/"],
config=graph_config,
)
diff --git a/tests/graphs/smart_scraper_ollama_test.py b/tests/graphs/smart_scraper_ollama_test.py
index 04862cd0..88af4a08 100644
--- a/tests/graphs/smart_scraper_ollama_test.py
+++ b/tests/graphs/smart_scraper_ollama_test.py
@@ -1,7 +1,9 @@
-"""
+"""
Module for testing th smart scraper class
"""
+
import pytest
+
from scrapegraphai.graphs import SmartScraperGraph
@@ -27,7 +29,7 @@ def test_scraping_pipeline(graph_config: dict):
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
result = smart_scraper_graph.run()
@@ -42,7 +44,7 @@ def test_get_execution_info(graph_config: dict):
smart_scraper_graph = SmartScraperGraph(
prompt="List me all the news with their description.",
source="https://perinim.github.io/projects",
- config=graph_config
+ config=graph_config,
)
smart_scraper_graph.run()
@@ -50,4 +52,3 @@ def test_get_execution_info(graph_config: dict):
graph_exec_info = smart_scraper_graph.get_execution_info()
assert graph_exec_info is not None
-
diff --git a/tests/graphs/smart_scraper_openai_test.py b/tests/graphs/smart_scraper_openai_test.py
index 0d25db91..90d6a7a7 100644
--- a/tests/graphs/smart_scraper_openai_test.py
+++ b/tests/graphs/smart_scraper_openai_test.py
@@ -3,12 +3,15 @@ Module for testing the smart scraper class
"""
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import SmartScraperGraph
load_dotenv()
+
@pytest.fixture
def graph_config():
"""Configuration of the graph"""
@@ -22,6 +25,7 @@ def graph_config():
"headless": False,
}
+
def test_scraping_pipeline(graph_config):
"""Start of the scraping pipeline"""
smart_scraper_graph = SmartScraperGraph(
@@ -33,7 +37,8 @@ def test_scraping_pipeline(graph_config):
result = smart_scraper_graph.run()
assert result is not None
- assert isinstance(result, dict)
+ assert isinstance(result, dict)
+
def test_get_execution_info(graph_config):
"""Get the execution info"""
diff --git a/tests/graphs/xml_scraper_openai_test.py b/tests/graphs/xml_scraper_openai_test.py
index c39877c5..cb2b4aa3 100644
--- a/tests/graphs/xml_scraper_openai_test.py
+++ b/tests/graphs/xml_scraper_openai_test.py
@@ -1,9 +1,12 @@
"""
xml_scraper_test
"""
+
import os
+
import pytest
from dotenv import load_dotenv
+
from scrapegraphai.graphs import XMLScraperGraph
from scrapegraphai.utils import convert_to_csv, convert_to_json, prettify_exec_info
@@ -13,6 +16,7 @@ load_dotenv()
# Define the test fixtures and helpers
# ************************************************
+
@pytest.fixture
def graph_config():
"""
@@ -27,6 +31,7 @@ def graph_config():
"verbose": False,
}
+
@pytest.fixture
def xml_content():
"""
@@ -36,13 +41,15 @@ def xml_content():
curr_dir = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(curr_dir, FILE_NAME)
- with open(file_path, 'r', encoding="utf-8") as file:
+ with open(file_path, "r", encoding="utf-8") as file:
return file.read()
+
# ************************************************
# Define the test cases
# ************************************************
+
def test_xml_scraper_graph(graph_config: dict, xml_content: str):
"""
Test the XMLScraperGraph scraping pipeline
@@ -50,13 +57,14 @@ def test_xml_scraper_graph(graph_config: dict, xml_content: str):
xml_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=xml_content, # Pass the XML content
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
assert result is not None
+
def test_xml_scraper_execution_info(graph_config: dict, xml_content: str):
"""
Test getting the execution info of XMLScraperGraph
@@ -64,7 +72,7 @@ def test_xml_scraper_execution_info(graph_config: dict, xml_content: str):
xml_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=xml_content, # Pass the XML content
- config=graph_config
+ config=graph_config,
)
xml_scraper_graph.run()
@@ -74,6 +82,7 @@ def test_xml_scraper_execution_info(graph_config: dict, xml_content: str):
assert graph_exec_info is not None
print(prettify_exec_info(graph_exec_info))
+
def test_xml_scraper_save_results(graph_config: dict, xml_content: str):
"""
Test saving the results of XMLScraperGraph to CSV and JSON
@@ -81,7 +90,7 @@ def test_xml_scraper_save_results(graph_config: dict, xml_content: str):
xml_scraper_graph = XMLScraperGraph(
prompt="List me all the authors, title and genres of the books",
source=xml_content, # Pass the XML content
- config=graph_config
+ config=graph_config,
)
result = xml_scraper_graph.run()
diff --git a/tests/inputs/books.xml b/tests/inputs/books.xml
index e3d1fe87..df9948ac 100644
--- a/tests/inputs/books.xml
+++ b/tests/inputs/books.xml
@@ -6,7 +6,7 @@
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
- <description>An in-depth look at creating applications
+ <description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
@@ -15,8 +15,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
- <description>A former architect battles corporate zombies,
- an evil sorceress, and her own childhood to become queen
+ <description>A former architect battles corporate zombies,
+ an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
@@ -25,8 +25,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
- <description>After the collapse of a nanotechnology
- society in England, the young survivors lay the
+ <description>After the collapse of a nanotechnology
+ society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
@@ -35,9 +35,9 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
- <description>In post-apocalypse England, the mysterious
- agent known only as Oberon helps to create a new life
- for the inhabitants of London. Sequel to Maeve
+ <description>In post-apocalypse England, the mysterious
+ agent known only as Oberon helps to create a new life
+ for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
@@ -46,8 +46,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
- <description>The two daughters of Maeve, half-sisters,
- battle one another for control of England. Sequel to
+ <description>The two daughters of Maeve, half-sisters,
+ battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
@@ -56,7 +56,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
- <description>When Carla meets Paul at an ornithology
+ <description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
@@ -65,7 +65,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
- <description>A deep sea diver finds true love twenty
+ <description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
@@ -84,7 +84,7 @@
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
- Uncertainty Device, James Salway discovers the problems
+ Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
@@ -93,7 +93,7 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
- <description>Microsoft's .NET initiative is explored in
+ <description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
@@ -102,8 +102,8 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
- <description>The Microsoft MSXML3 parser is covered in
- detail, with attention to XML DOM interfaces, XSLT processing,
+ <description>The Microsoft MSXML3 parser is covered in
+ detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
@@ -113,8 +113,8 @@
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
- looking at how Visual Basic, Visual C++, C#, and ASP+ are
- integrated into a comprehensive development
+ looking at how Visual Basic, Visual C++, C#, and ASP+ are
+ integrated into a comprehensive development
environment.</description>
</book>
-</catalog>
\ No newline at end of file
+</catalog>
diff --git a/tests/inputs/example.json b/tests/inputs/example.json
index 2263184c..1cce449a 100644
--- a/tests/inputs/example.json
+++ b/tests/inputs/example.json
@@ -179,4 +179,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/tests/inputs/plain_html_example.txt b/tests/inputs/plain_html_example.txt
index 78f814ae..2476565e 100644
--- a/tests/inputs/plain_html_example.txt
+++ b/tests/inputs/plain_html_example.txt
@@ -2,16 +2,16 @@
<header>
<nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top">
<div class="container">
- <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
+ <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
<div class="collapse navbar-collapse text-right" id="navbarNav">
<ul class="navbar-nav ml-auto flex-nowrap">
<li class="nav-item "> <a class="nav-link" href="/">About</a> </li>
<li class="nav-item dropdown active">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
+ <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
- <a class="dropdown-item" href="/projects/">Projects</a>
+ <a class="dropdown-item" href="/projects/">Projects</a>
<div class="dropdown-divider"></div>
- <a class="dropdown-item" href="/competitions/">Competitions</a>
+ <a class="dropdown-item" href="/competitions/">Competitions</a>
</div>
</li>
<li class="nav-item "> <a class="nav-link" href="/cv/">CV</a> </li>
@@ -100,6 +100,6 @@
</div>
<footer class="fixed-bottom">
<div class="container mt-0"> © Copyright 2023 Marco Perini. Powered by <a href="https://jekyllrb.com/" target="_blank" rel="external nofollow noopener">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio" rel="external nofollow noopener" target="_blank">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank" rel="external nofollow noopener">GitHub Pages</a>. </div>
- </footer>
+ </footer>
<div class="hiddendiv common"></div>
-</body>
\ No newline at end of file
+</body>
diff --git a/tests/inputs/username.csv b/tests/inputs/username.csv
index 006ac8e6..0d32afd0 100644
--- a/tests/inputs/username.csv
+++ b/tests/inputs/username.csv
@@ -4,4 +4,3 @@ grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
-
diff --git a/tests/nodes/fetch_node_test.py b/tests/nodes/fetch_node_test.py
index 7e03d153..91144daa 100644
--- a/tests/nodes/fetch_node_test.py
+++ b/tests/nodes/fetch_node_test.py
@@ -1,6 +1,8 @@
-from scrapegraphai.nodes import FetchNode
from langchain_core.documents import Document
+from scrapegraphai.nodes import FetchNode
+
+
def test_fetch_html(mocker):
title = "ScrapeGraph AI"
link_url = "https://github.com/VinciGit00/Scrapegraph-ai"
@@ -31,7 +33,10 @@ def test_fetch_html(mocker):
assert result is not None
assert "ScrapeGraph AI" in doc.page_content
assert "https://github.com/VinciGit00/Scrapegraph-ai" in doc.page_content
- assert "https://raw.githubusercontent.com/VinciGit00/Scrapegraph-ai/main/docs/assets/scrapegraphai_logo.png" in doc.page_content
+ assert (
+ "https://raw.githubusercontent.com/VinciGit00/Scrapegraph-ai/main/docs/assets/scrapegraphai_logo.png"
+ in doc.page_content
+ )
def test_fetch_json():
diff --git a/tests/nodes/inputs/books.xml b/tests/nodes/inputs/books.xml
index e3d1fe87..df9948ac 100644
--- a/tests/nodes/inputs/books.xml
+++ b/tests/nodes/inputs/books.xml
@@ -6,7 +6,7 @@
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
- <description>An in-depth look at creating applications
+ <description>An in-depth look at creating applications
with XML.</description>
</book>
<book id="bk102">
@@ -15,8 +15,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
- <description>A former architect battles corporate zombies,
- an evil sorceress, and her own childhood to become queen
+ <description>A former architect battles corporate zombies,
+ an evil sorceress, and her own childhood to become queen
of the world.</description>
</book>
<book id="bk103">
@@ -25,8 +25,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
- <description>After the collapse of a nanotechnology
- society in England, the young survivors lay the
+ <description>After the collapse of a nanotechnology
+ society in England, the young survivors lay the
foundation for a new society.</description>
</book>
<book id="bk104">
@@ -35,9 +35,9 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
- <description>In post-apocalypse England, the mysterious
- agent known only as Oberon helps to create a new life
- for the inhabitants of London. Sequel to Maeve
+ <description>In post-apocalypse England, the mysterious
+ agent known only as Oberon helps to create a new life
+ for the inhabitants of London. Sequel to Maeve
Ascendant.</description>
</book>
<book id="bk105">
@@ -46,8 +46,8 @@
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
- <description>The two daughters of Maeve, half-sisters,
- battle one another for control of England. Sequel to
+ <description>The two daughters of Maeve, half-sisters,
+ battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
<book id="bk106">
@@ -56,7 +56,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-09-02</publish_date>
- <description>When Carla meets Paul at an ornithology
+ <description>When Carla meets Paul at an ornithology
conference, tempers fly as feathers get ruffled.</description>
</book>
<book id="bk107">
@@ -65,7 +65,7 @@
<genre>Romance</genre>
<price>4.95</price>
<publish_date>2000-11-02</publish_date>
- <description>A deep sea diver finds true love twenty
+ <description>A deep sea diver finds true love twenty
thousand leagues beneath the sea.</description>
</book>
<book id="bk108">
@@ -84,7 +84,7 @@
<price>6.95</price>
<publish_date>2000-11-02</publish_date>
<description>After an inadvertant trip through a Heisenberg
- Uncertainty Device, James Salway discovers the problems
+ Uncertainty Device, James Salway discovers the problems
of being quantum.</description>
</book>
<book id="bk110">
@@ -93,7 +93,7 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-09</publish_date>
- <description>Microsoft's .NET initiative is explored in
+ <description>Microsoft's .NET initiative is explored in
detail in this deep programmer's reference.</description>
</book>
<book id="bk111">
@@ -102,8 +102,8 @@
<genre>Computer</genre>
<price>36.95</price>
<publish_date>2000-12-01</publish_date>
- <description>The Microsoft MSXML3 parser is covered in
- detail, with attention to XML DOM interfaces, XSLT processing,
+ <description>The Microsoft MSXML3 parser is covered in
+ detail, with attention to XML DOM interfaces, XSLT processing,
SAX and more.</description>
</book>
<book id="bk112">
@@ -113,8 +113,8 @@
<price>49.95</price>
<publish_date>2001-04-16</publish_date>
<description>Microsoft Visual Studio 7 is explored in depth,
- looking at how Visual Basic, Visual C++, C#, and ASP+ are
- integrated into a comprehensive development
+ looking at how Visual Basic, Visual C++, C#, and ASP+ are
+ integrated into a comprehensive development
environment.</description>
</book>
-</catalog>
\ No newline at end of file
+</catalog>
diff --git a/tests/nodes/inputs/example.json b/tests/nodes/inputs/example.json
index 2263184c..1cce449a 100644
--- a/tests/nodes/inputs/example.json
+++ b/tests/nodes/inputs/example.json
@@ -179,4 +179,4 @@
}
}
]
-}
\ No newline at end of file
+}
diff --git a/tests/nodes/inputs/plain_html_example.txt b/tests/nodes/inputs/plain_html_example.txt
index 78f814ae..2476565e 100644
--- a/tests/nodes/inputs/plain_html_example.txt
+++ b/tests/nodes/inputs/plain_html_example.txt
@@ -2,16 +2,16 @@
<header>
<nav id="navbar" class="navbar navbar-light navbar-expand-sm fixed-top">
<div class="container">
- <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
+ <a class="navbar-brand title font-weight-lighter" href="/"><span class="font-weight-bold">Marco&nbsp;</span>Perini</a> <button class="navbar-toggler collapsed ml-auto" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar top-bar"></span> <span class="icon-bar middle-bar"></span> <span class="icon-bar bottom-bar"></span> </button>
<div class="collapse navbar-collapse text-right" id="navbarNav">
<ul class="navbar-nav ml-auto flex-nowrap">
<li class="nav-item "> <a class="nav-link" href="/">About</a> </li>
<li class="nav-item dropdown active">
- <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
+ <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Projects<span class="sr-only">(current)</span></a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
- <a class="dropdown-item" href="/projects/">Projects</a>
+ <a class="dropdown-item" href="/projects/">Projects</a>
<div class="dropdown-divider"></div>
- <a class="dropdown-item" href="/competitions/">Competitions</a>
+ <a class="dropdown-item" href="/competitions/">Competitions</a>
</div>
</li>
<li class="nav-item "> <a class="nav-link" href="/cv/">CV</a> </li>
@@ -100,6 +100,6 @@
</div>
<footer class="fixed-bottom">
<div class="container mt-0"> © Copyright 2023 Marco Perini. Powered by <a href="https://jekyllrb.com/" target="_blank" rel="external nofollow noopener">Jekyll</a> with <a href="https://github.com/alshedivat/al-folio" rel="external nofollow noopener" target="_blank">al-folio</a> theme. Hosted by <a href="https://pages.github.com/" target="_blank" rel="external nofollow noopener">GitHub Pages</a>. </div>
- </footer>
+ </footer>
<div class="hiddendiv common"></div>
-</body>
\ No newline at end of file
+</body>
diff --git a/tests/nodes/inputs/username.csv b/tests/nodes/inputs/username.csv
index 006ac8e6..0d32afd0 100644
--- a/tests/nodes/inputs/username.csv
+++ b/tests/nodes/inputs/username.csv
@@ -4,4 +4,3 @@ grey07;2070;Laura;Grey
johnson81;4081;Craig;Johnson
jenkins46;9346;Mary;Jenkins
smith79;5079;Jamie;Smith
-
diff --git a/tests/nodes/robot_node_test.py b/tests/nodes/robot_node_test.py
index 62527dda..692b6062 100644
--- a/tests/nodes/robot_node_test.py
+++ b/tests/nodes/robot_node_test.py
@@ -1,8 +1,11 @@
-import pytest
from unittest.mock import MagicMock
+
+import pytest
from langchain_community.chat_models import ChatOllama
+
from scrapegraphai.nodes import RobotsNode
+
@pytest.fixture
def mock_llm_model():
mock_model = MagicMock()
@@ -10,21 +13,23 @@ def mock_llm_model():
mock_model.__call__ = MagicMock(return_value=["yes"])
return mock_model
+
@pytest.fixture
def robots_node(mock_llm_model):
return RobotsNode(
input="url",
output=["is_scrapable"],
- node_config={"llm_model": mock_llm_model, "headless": False}
+ node_config={"llm_model": mock_llm_model, "headless": False},
)
+
def test_robots_node_scrapable(robots_node):
- state = {
- "url": "https://perinim.github.io/robots.txt"
- }
+ state = {"url": "https://perinim.github.io/robots.txt"}
# Mocking AsyncChromiumLoader to return a fake robots.txt content
- robots_node.AsyncChromiumLoader = MagicMock(return_value=MagicMock(load=MagicMock(return_value="User-agent: *\nAllow: /")))
+ robots_node.AsyncChromiumLoader = MagicMock(
+ return_value=MagicMock(load=MagicMock(return_value="User-agent: *\nAllow: /"))
+ )
# Execute the node
result_state, result = robots_node.execute(state)
@@ -33,13 +38,16 @@ def test_robots_node_scrapable(robots_node):
assert result_state["is_scrapable"] == "yes"
assert result == ("is_scrapable", "yes")
+
def test_robots_node_not_scrapable(robots_node):
- state = {
- "url": "https://twitter.com/home"
- }
+ state = {"url": "https://twitter.com/home"}
# Mocking AsyncChromiumLoader to return a fake robots.txt content
- robots_node.AsyncChromiumLoader = MagicMock(return_value=MagicMock(load=MagicMock(return_value="User-agent: *\nDisallow: /")))
+ robots_node.AsyncChromiumLoader = MagicMock(
+ return_value=MagicMock(
+ load=MagicMock(return_value="User-agent: *\nDisallow: /")
+ )
+ )
# Mock the LLM response to return "no"
robots_node.llm_model.__call__.return_value = ["no"]
@@ -48,13 +56,16 @@ def test_robots_node_not_scrapable(robots_node):
with pytest.raises(ValueError):
robots_node.execute(state)
+
def test_robots_node_force_scrapable(robots_node):
- state = {
- "url": "https://twitter.com/home"
- }
+ state = {"url": "https://twitter.com/home"}
# Mocking AsyncChromiumLoader to return a fake robots.txt content
- robots_node.AsyncChromiumLoader = MagicMock(return_value=MagicMock(load=MagicMock(return_value="User-agent: *\nDisallow: /")))
+ robots_node.AsyncChromiumLoader = MagicMock(
+ return_value=MagicMock(
+ load=MagicMock(return_value="User-agent: *\nDisallow: /")
+ )
+ )
# Mock the LLM response to return "no"
robots_node.llm_model.__call__.return_value = ["no"]
@@ -69,5 +80,6 @@ def test_robots_node_force_scrapable(robots_node):
assert result_state["is_scrapable"] == "no"
assert result == ("is_scrapable", "no")
+
if __name__ == "__main__":
pytest.main()
diff --git a/tests/nodes/search_internet_node_test.py b/tests/nodes/search_internet_node_test.py
index 8e198448..67792424 100644
--- a/tests/nodes/search_internet_node_test.py
+++ b/tests/nodes/search_internet_node_test.py
@@ -1,20 +1,19 @@
import unittest
+
from langchain_community.chat_models import ChatOllama
+
from scrapegraphai.nodes import SearchInternetNode
+
class TestSearchInternetNode(unittest.TestCase):
def setUp(self):
# Configuration for the graph
self.graph_config = {
- "llm": {
- "model": "llama3",
- "temperature": 0,
- "streaming": True
- },
+ "llm": {"model": "llama3", "temperature": 0, "streaming": True},
"search_engine": "google",
"max_results": 3,
- "verbose": True
+ "verbose": True,
}
# Define the model
@@ -28,15 +27,13 @@ class TestSearchInternetNode(unittest.TestCase):
"llm_model": self.llm_model,
"search_engine": self.graph_config["search_engine"],
"max_results": self.graph_config["max_results"],
- "verbose": self.graph_config["verbose"]
- }
+ "verbose": self.graph_config["verbose"],
+ },
)
def test_execute_search_node(self):
# Initial state
- state = {
- "user_input": "What is the capital of France?"
- }
+ state = {"user_input": "What is the capital of France?"}
# Expected output
expected_output = {
@@ -44,8 +41,8 @@ class TestSearchInternetNode(unittest.TestCase):
"search_results": [
"https://en.wikipedia.org/wiki/Paris",
"https://en.wikipedia.org/wiki/France",
- "https://en.wikipedia.org/wiki/%C3%8Ele-de-France"
- ]
+ "https://en.wikipedia.org/wiki/%C3%8Ele-de-France",
+ ],
}
# Execute the node
@@ -54,5 +51,6 @@ class TestSearchInternetNode(unittest.TestCase):
# Assert the results
self.assertEqual(result, expected_output)
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/nodes/search_link_node_test.py b/tests/nodes/search_link_node_test.py
index 1f8c5a58..5c64e470 100644
--- a/tests/nodes/search_link_node_test.py
+++ b/tests/nodes/search_link_node_test.py
@@ -1,7 +1,10 @@
+from unittest.mock import MagicMock, patch
+
import pytest
from langchain_community.chat_models import ChatOllama
+
from scrapegraphai.nodes import SearchLinkNode
-from unittest.mock import patch, MagicMock
+
@pytest.fixture
def setup():
@@ -10,11 +13,7 @@ def setup():
"""
# Define the configuration for the graph
graph_config = {
- "llm": {
- "model_name": "ollama/llama3",
- "temperature": 0,
- "streaming": True
- },
+ "llm": {"model_name": "ollama/llama3", "temperature": 0, "streaming": True},
}
# Instantiate the LLM model with the configuration
@@ -24,10 +23,7 @@ def setup():
search_link_node = SearchLinkNode(
input=["user_prompt", "parsed_content_chunks"],
output=["relevant_links"],
- node_config={
- "llm_model": llm_model,
- "verbose": False
- }
+ node_config={"llm_model": llm_model, "verbose": False},
)
# Define the initial state for the node
@@ -37,11 +33,12 @@ def setup():
{"page_content": "Example page content 1"},
{"page_content": "Example page content 2"},
# Add more example page content dictionaries as needed
- ]
+ ],
}
return search_link_node, initial_state
+
def test_search_link_node(setup):
"""
Test the SearchLinkNode execution.
@@ -49,7 +46,11 @@ def test_search_link_node(setup):
search_link_node, initial_state = setup
# Patch the execute method to avoid actual network calls and return a mock response
- with patch.object(SearchLinkNode, 'execute', return_value={"relevant_links": ["http://example.com"]}) as mock_execute:
+ with patch.object(
+ SearchLinkNode,
+ "execute",
+ return_value={"relevant_links": ["http://example.com"]},
+ ) as mock_execute:
result = search_link_node.execute(initial_state)
# Check if the result is not None
diff --git a/tests/utils/convert_to_md_test.py b/tests/utils/convert_to_md_test.py
index 72270913..f4ea1d4a 100644
--- a/tests/utils/convert_to_md_test.py
+++ b/tests/utils/convert_to_md_test.py
@@ -1,30 +1,36 @@
import pytest
+
from scrapegraphai.utils.convert_to_md import convert_to_md
+
def test_basic_html_to_md():
html = "<html><body><p>This is a paragraph.</p><h1>This is a heading.</h1></body></html>"
assert convert_to_md(html) is not None
+
def test_html_with_links_and_images():
html = '<p>This is a <a href="https://example.com">link</a> and this is an <img src="https://example.com/image.jpg" alt="image"></p>'
assert convert_to_md(html) is not None
+
def test_html_with_tables():
- html = '''
+ html = """
<table>
<tr><th>Header 1</th><th>Header 2</th></tr>
<tr><td>Row 1, Cell 1</td><td>Row 1, Cell 2</td></tr>
<tr><td>Row 2, Cell 1</td><td>Row 2, Cell 2</td></tr>
</table>
- '''
+ """
assert convert_to_md(html) is not None
+
def test_empty_html():
html = ""
assert convert_to_md(html) is not None
+
def test_complex_html_structure():
- html = '''
+ html = """
<html>
<body>
<h1>Main Heading</h1>
@@ -37,5 +43,5 @@ def test_complex_html_structure():
<p>Another paragraph with a <a href="https://example.com">link</a>.</p>
</body>
</html>
- '''
+ """
assert convert_to_md(html) is not None
diff --git a/tests/utils/copy_utils_test.py b/tests/utils/copy_utils_test.py
index 4f684088..607d2c53 100644
--- a/tests/utils/copy_utils_test.py
+++ b/tests/utils/copy_utils_test.py
@@ -1,13 +1,16 @@
import copy
+
import pytest
+from pydantic.v1 import BaseModel
# Assuming the custom_deepcopy function is imported or defined above this line
from scrapegraphai.utils.copy import DeepCopyError, safe_deepcopy
-from pydantic.v1 import BaseModel
+
class PydantObject(BaseModel):
value: int
+
class NormalObject:
def __init__(self, value):
self.value = value
@@ -109,8 +112,6 @@ def test_circular_reference():
assert copy_obj[0] is copy_obj
-
-
def test_deepcopy_object_without_dict():
original = {"origin": WithoutDict(10)}
copy_obj = safe_deepcopy(original)
@@ -149,11 +150,13 @@ def test_deepcopy_object_without_dict():
assert copy_obj_item.value == original_item.value
assert copy_obj_item is original_item
+
def test_unhandled_type():
with pytest.raises(DeepCopyError):
original = {"origin": NonCopyableObject(10)}
copy_obj = safe_deepcopy(original)
+
def test_client():
llm_instance_config = {
"model": "moonshot-v1-8k",
@@ -165,28 +168,32 @@ def test_client():
llm_model_instance = MoonshotChat(**llm_instance_config)
copy_obj = safe_deepcopy(llm_model_instance)
-
+
assert copy_obj
- assert hasattr(copy_obj, 'callbacks')
+ assert hasattr(copy_obj, "callbacks")
+
def test_circular_reference_in_dict():
original = {}
- original['self'] = original # Create a circular reference
+ original["self"] = original # Create a circular reference
copy_obj = safe_deepcopy(original)
-
+
# Check that the copy is a different object
assert copy_obj is not original
# Check that the circular reference is maintained in the copy
- assert copy_obj['self'] is copy_obj
+ assert copy_obj["self"] is copy_obj
+
def test_with_pydantic():
original = PydantObject(value=1)
copy_obj = safe_deepcopy(original)
assert copy_obj.value == original.value
- assert copy_obj is not original
+ assert copy_obj is not original
+
def test_with_boto3():
import boto3
+
boto_client = boto3.client("bedrock-runtime", region_name="us-west-2")
copy_obj = safe_deepcopy(boto_client)
- assert copy_obj == boto_client
\ No newline at end of file
+ assert copy_obj == boto_client
diff --git a/tests/utils/parse_state_keys_test.py b/tests/utils/parse_state_keys_test.py
index d91355f1..4bfaf928 100644
--- a/tests/utils/parse_state_keys_test.py
+++ b/tests/utils/parse_state_keys_test.py
@@ -1,7 +1,9 @@
"""
-Parse_state_key test module
+Parse_state_key test module
"""
+
import pytest
+
from scrapegraphai.utils.parse_state_keys import parse_expression
diff --git a/tests/utils/research_web_test.py b/tests/utils/research_web_test.py
index 46630625..a4a37191 100644
--- a/tests/utils/research_web_test.py
+++ b/tests/utils/research_web_test.py
@@ -1,5 +1,8 @@
import pytest
-from scrapegraphai.utils.research_web import search_on_web # Replace with actual path to your file
+
+from scrapegraphai.utils.research_web import ( # Replace with actual path to your file
+ search_on_web,
+)
def test_google_search():
@@ -8,6 +11,7 @@ def test_google_search():
assert len(results) == 2
# You can further assert if the results actually contain 'test query' in the title/snippet using additional libraries
+
def test_bing_search():
"""Tests search_on_web with Bing search engine."""
results = search_on_web("test query", search_engine="Bing", max_results=1)