<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Bex T. on Medium]]></title>
        <description><![CDATA[Stories by Bex T. on Medium]]></description>
        <link>https://medium.com/@ibexorigin?source=rss-39db050c2ac2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*utsNunS-76Mnd3RMNXz5MA.png</url>
            <title>Stories by Bex T. on Medium</title>
            <link>https://medium.com/@ibexorigin?source=rss-39db050c2ac2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:48:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibexorigin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[End-to-end Portfolio Project: Building Amazon Price Tracker in Python]]></title>
            <link>https://medium.datadriveninvestor.com/end-to-end-portfolio-project-building-amazon-price-tracker-in-python-d3906b1aaed1?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3906b1aaed1</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 06:26:13 GMT</pubDate>
            <atom:updated>2024-12-16T07:48:44.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>That sends notifications to your phone when prices drop</h4><p>There is a lot to be said about the psychology of discounts. For example, buying a discounted item we don’t need isn’t saving money at all - it’s falling for one of the oldest sales tactics. However, there are legitimate cases where waiting for a price drop on items you actually need makes perfect sense.</p><p>The challenge is that e-commerce websites constantly run flash sales and temporary discounts, but these deals often disappear as quickly as they appear. Missing these brief windows of opportunity can be frustrating.</p><p>That’s where automation comes in. In this guide, we’ll build a Python application that monitors product prices across any e-commerce website and instantly notifies you when prices drop on items you’re actually interested in. Here is a sneak peek of the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB1V7sWXczJRUiTESmJN9A.png" /></figure><p>The app has a simple appearance but provides complete functionality:</p><ul><li>It has a minimalistic UI to add or remove products from the tracker</li><li>A simple dashboard to display the price history for each product</li><li>Controls for setting the price drop threshold in percentages</li><li>A notification system that sends Discord alerts when a tracked item’s price drops</li><li>A scheduling system that updates the product prices on an interval you specify</li><li>Runs for free for as long as you want</li></ul><p>Even though the title says “Amazon price tracker”, the app will work for any e-commerce website you can imagine (except eBay, for some reason).</p><p>So, let’s get started building this Amazon price tracker.</p><h3>The Toolstack We Will Use</h3><p>The app will be built using Python and these libraries::</p><ul><li><a href="https://www.streamlit.io/">Streamlit</a> for the UI</li><li><a href="https://www.firecrawl.dev/">Firecrawl</a> for AI-based scraping of e-commerce websites</li><li><a href="https://www.sqlalchemy.org/">SQLAlchemy</a> for database management</li></ul><p>In addition to Python, we will use these platforms:</p><ul><li>Discord for notifications</li><li>GitHub for hosting the app</li><li>GitHub Actions for running the app on a schedule</li><li>Supabase for hosting a free Postgres database instance</li></ul><h3>Building an Amazon Price Tracker App Step-by-step</h3><p>Since this project involves multiple components working together, we’ll take a top-down approach rather than building individual pieces first. This approach makes it easier to understand how everything fits together, since we’ll introduce each tool only when it’s needed. The benefits of this strategy will become clear as we progress through the tutorial.</p><h4>Step 1: Setting up the environment</h4><p>First, let’s create a dedicated environment on our machines to work on the project:</p><pre>mkdir automated-price-tracker<br>cd automated-price-tracker<br>python -m venv .venv<br>source .venv/bin/activate</pre><p>These commands create a working directory and activate a virtual environment. Next, create a new script called ui.py for designing the user interface with Streamlit.</p><pre>touch ui.py</pre><p>Then, install Streamlit:</p><pre>pip install streamlit</pre><p>Next, create a requirements.txt file and add Streamlit as the first dependency:</p><pre>touch requirements.txt<br>echo &quot;streamlit\n&quot; &gt;&gt; requirements.txt</pre><p>Since the code will be hosted on GitHub, we need to initialize Git and create a .gitignore file:</p><pre>git init<br>touch .gitignore<br>echo &quot;.venv&quot; &gt;&gt; .gitignore  # Add the virtual env folder<br>git commit -m &quot;Initial commit&quot;</pre><h4>Step 2: Add a sidebar to the UI for product input</h4><p>Let’s take a look at the final product one more time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB1V7sWXczJRUiTESmJN9A.png" /></figure><p>It has two sections: the sidebar and the main dashboard. Since the first thing you do when launching this app would be adding products, we will start building the sidebar first. Open ui.py and paste the following code:</p><pre>import streamlit as st<br><br># Set up sidebar<br>with st.sidebar:<br>    st.title(&quot;Add New Product&quot;)<br>    product_url = st.text_input(&quot;Product URL&quot;)<br>    add_button = st.button(&quot;Add Product&quot;)<br><br># Main content<br>st.title(&quot;Price Tracker Dashboard&quot;)<br>st.markdown(&quot;## Tracked Products&quot;)</pre><p>The code snippet above sets up a basic Streamlit web application with two main sections. In the sidebar, it creates a form for adding new products with a text input field for the product URL and an “Add Product” button. The main content area contains a dashboard title and a section header for tracked products. The code uses Streamlit’s st.sidebar context manager to create the sidebar layout and basic Streamlit components like st.title, st.text_input, and st.button to build the user interface elements.</p><p>To see how this app looks like, run the following command:</p><pre>streamlit run ui.py</pre><p>Now, let’s add a commit to save our progress:</p><pre>git add .<br>git commit -m &quot;Add a sidebar to the basic UI&quot;</pre><h4>Step 3: Add a feature to check if input URL is valid</h4><p>In the next step, we want to add some restrictions to the input field like checking if the passed URL is valid. For this, create a new file called utils.py where we write additional utility functions for our app:</p><pre>touch utils.py</pre><p>Inside the script, paste following code:</p><pre># utils.py<br>from urllib.parse import urlparse<br>import re<br><br><br>def is_valid_url(url: str) -&gt; bool:<br>    try:<br>        # Parse the URL<br>        result = urlparse(url)<br><br>        # Check if scheme and netloc are present<br>        if not all([result.scheme, result.netloc]):<br>            return False<br><br>        # Check if scheme is http or https<br>        if result.scheme not in [&quot;http&quot;, &quot;https&quot;]:<br>            return False<br><br>        # Basic regex pattern for domain validation<br>        domain_pattern = (<br>            r&quot;^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z]{2,})+$&quot;<br>        )<br>        if not re.match(domain_pattern, result.netloc):<br>            return False<br><br>        return True<br><br>    except Exception:<br>        return False</pre><p>The above function is_valid_url() validates URLs by checking several criteria:</p><ol><li>It verifies the URL has both a scheme (http/https) and domain name</li><li>It ensures the scheme is specifically http or https</li><li>It validates the domain name format using regex to check for valid characters and TLD</li><li>It returns True only if all checks pass, False otherwise</li></ol><p>Let’s use this function in our ui.py file. Here is the modified code:</p><pre>import streamlit as st<br>from utils import is_valid_url<br><br><br># Set up sidebar<br>with st.sidebar:<br>    st.title(&quot;Add New Product&quot;)<br>    product_url = st.text_input(&quot;Product URL&quot;)<br>    add_button = st.button(&quot;Add Product&quot;)<br><br>    if add_button:<br>        if not product_url:<br>            st.error(&quot;Please enter a product URL&quot;)<br>        elif not is_valid_url(product_url):<br>            st.error(&quot;Please enter a valid URL&quot;)<br>        else:<br>            st.success(&quot;Product is now being tracked!&quot;)<br><br># Main content<br>...</pre><p>Here is what’s new:</p><ol><li>We added URL validation using the is_valid_url() function from utils.py</li><li>When the button is clicked, we perform validation:</li></ol><ul><li>Check if URL is empty</li><li>Validate URL format using is_valid_url()</li></ul><p>3. User feedback is provided through error/success messages:</p><ul><li>Error shown for empty URL</li><li>Error shown for invalid URL format</li><li>Success message when URL passes validation</li></ul><p>Rerun the Streamlit app again and see if our validation works. Then, return to your terminal to commit the changes we’ve made:</p><pre>git add .<br>git commit -m &quot;Add a feature to check URL validity&quot;</pre><h4>Step 4: Scrape the input URL for product details</h4><p>When a valid URL is entered and the add button is clicked, we need to implement product scraping functionality instead of just showing a success message. The system should:</p><ol><li>Immediately scrape the product URL to extract key details:</li></ol><ul><li>Product name</li><li>Current price</li><li>Main product image</li><li>Brand name</li><li>Other relevant attributes</li></ul><p>2. Store these details in a database to enable:</p><ul><li>Regular price monitoring</li><li>Historical price tracking</li><li>Price change alerts</li><li>Product status updates</li></ul><p>For the scraper, we will use <a href="https://www.firecrawl.dev/blog/firecrawl.dev">Firecrawl</a>, an AI-based scraping API for extracting webpage data without manual HTML parsing. This solution provides several advantages:</p><ol><li>No website HTML code analysis required for element selection</li><li>Resilient to HTML structure changes through AI-based element detection</li><li>Universal compatibility with product webpages due to structure-agnostic approach</li><li>Reliable website blocker bypass via robust API infrastructure</li></ol><p>First, create a new file called scraper.py:</p><pre>touch scraper.py</pre><p>Then, install these three libraries:</p><pre>pip install firecrawl-py pydantic python-dotenv<br>echo &quot;firecrawl-py\npydantic\npython-dotenv\n&quot; &gt;&gt; requirements.txt  # Add them to dependencies</pre><p>firecrawl-py is the Python SDK for Firecrawl scraping engine, pydantic is a data validation library that helps enforce data types and structure through Python class definitions, and python-dotenv is a library that loads environment variables from a .env file into your Python application.</p><p>With that said, head over to the Firecrawl website and <a href="https://www.firecrawl.dev/">sign up for a free account</a> (the free plan will work fine). You will be given an API key, which you should copy.</p><p>Then, create a .env file in your terminal and add the API key as an environment variable:</p><pre>touch .env<br>echo &quot;FIRECRAWL_API_KEY=&#39;YOUR-API-KEY-HERE&#39;&quot; &gt;&gt; .env<br>echo &quot;.env&quot; &gt;&gt; .gitignore  # Ignore .env files in Git</pre><p>The .env file is used to securely store sensitive configuration values like API keys that shouldn’t be committed to version control. By storing the Firecrawl API key in .env and adding it to .gitignore, we ensure it stays private while still being accessible to our application code. This is a security best practice to avoid exposing credentials in source control.</p><p>Now, we can start writing the scraper.py:</p><pre>from firecrawl import FirecrawlApp<br>from pydantic import BaseModel, Field<br>from dotenv import load_dotenv<br>from datetime import datetime<br><br>load_dotenv()<br><br>app = FirecrawlApp()</pre><p>Here, load_dotenv() function reads the .env file you have in your working directory and loads the environment variables inside, including the Firecrawl API key. When you create an instance of FirecrawlApp class, the API key is automatically detected to establish a connection between your script and the scraping engine in the form of the app variable.</p><p>Now, we create a Pydantic class (usually called a model) that defines the details we want to scrape from each product:</p><pre>class Product(BaseModel):<br>    &quot;&quot;&quot;Schema for creating a new product&quot;&quot;&quot;<br><br>    url: str = Field(description=&quot;The URL of the product&quot;)<br>    name: str = Field(description=&quot;The product name/title&quot;)<br>    price: float = Field(description=&quot;The current price of the product&quot;)<br>    currency: str = Field(description=&quot;Currency code (USD, EUR, etc)&quot;)<br>    main_image_url: str = Field(description=&quot;The URL of the main image of the product&quot;)</pre><p>Pydantic models may be completely new to you, so let’s break down the Product model:</p><ul><li>The url field stores the product page URL we want to track</li><li>The name field stores the product title/name that will be scraped</li><li>The price field stores the current price as a float</li><li>The currency field stores the 3-letter currency code (e.g. USD, EUR)</li><li>The main_image_url field stores the URL of the product’s main image</li></ul><p>Each field is typed and has a description that documents its purpose using the Field class. These descriptions are especially important for Firecrawl since it uses them to automatically locate the relevant HTML elements containing the data we want.</p><p>Now, let’s create a function to call the engine to scrape URL’s based on the schema above:</p><pre>def scrape_product(url: str):<br>    extracted_data = app.scrape_url(<br>        url,<br>        params={<br>            &quot;formats&quot;: [&quot;extract&quot;],<br>            &quot;extract&quot;: {&quot;schema&quot;: Product.model_json_schema()},<br>        },<br>    )<br><br>    # Add the scraping date to the extracted data<br>    extracted_data[&quot;extract&quot;][&quot;timestamp&quot;] = datetime.utcnow()<br><br>    return extracted_data[&quot;extract&quot;]<br><br><br>if __name__ == &quot;__main__&quot;:<br>    product = &quot;https://www.amazon.com/gp/product/B002U21ZZK/&quot;<br><br>    print(scrape_product(product))</pre><p>The code above defines a function called scrape_product that takes a URL as input and uses it to scrape product information. Here’s how it works:</p><p>The function calls app.scrape_url with two parameters:</p><ol><li>The product URL to scrape</li><li>A params dictionary that configures the scraping:</li></ol><ul><li>It specifies we want to use the “extract” format</li><li>It provides our Product Pydantic model schema as the extraction template as a JSON object</li></ul><p>The scraper will attempt to find and extract data that matches our Product schema fields - the URL, name, price, currency, and image URL.</p><p>The function returns just the “extract” portion of the scraped data, which contains the structured product information. extract returns a dictionary to which we add the date of the scraping as it will be important later on.</p><p>Let’s test the script by running it:</p><pre>python scraper.py</pre><p>You should get an output like this:</p><pre>{<br>    &#39;url&#39;: &#39;https://www.amazon.com/dp/B002U21ZZK&#39;, <br>    &#39;name&#39;: &#39;MOVA Globe Earth with Clouds 4.5&quot;&#39;, <br>    &#39;price&#39;: 212, <br>    &#39;currency&#39;: &#39;USD&#39;, <br>    &#39;main_image_url&#39;: &#39;https://m.media-amazon.com/images/blog/price-tracking/I/41bQ3Y58y3L._AC_.jpg&#39;, <br>    &#39;timestamp&#39;: &#39;2024-12-05 13-20&#39;<br>}</pre><p>The output shows that a <a href="https://www.amazon.com/dp/B002U21ZZK">MOVA Globe</a> costs USD 212 on Amazon at the time of writing this article. You can test the script for any other website that contains the information we are looking for (except eBay):</p><ul><li>Price</li><li>Product name/title</li><li>Main image URL</li></ul><p>One key advantage of using Firecrawl is that it returns data in a consistent dictionary format across all websites. Unlike HTML-based scrapers like BeautifulSoup or Scrapy which require custom code for each site and can break when website layouts change, Firecrawl uses AI to understand and extract the requested data fields regardless of the underlying HTML structure.</p><p>Finish this step by committing the new changes to Git:</p><pre>git add .<br>git commit -m &quot;Implement a Firecrawl scraper for products&quot;</pre><h4>Step 5: Storing new products in a PostgreSQL database</h4><p>If we want to check product prices regularly, we need to have an online database. In this case, Postgres is the best option since it’s reliable, scalable, and has great support for storing time-series data like price histories.</p><p>There are many platforms for hosting Postgres instances but the one I find the easiest and fastest to set up is Supabase. So, please head over to <a href="https://supabase.com/">the Supabase website</a> and create your free account. During the sign-up process, you will be given a password, which you should save somewhere safe on your machine.</p><p>Then, in a few minutes, your free Postgres instance comes online. To connect to this instance, click on Home in the left sidebar and then, “Connect”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V_mvxksQVWhkint9.png" /></figure><p>You will be shown your database connection string with a placeholder for the password you copied. You should paste this string in your .env file with your password added to the .env file:</p><pre>echo &#39;POSTGRES_URL=&quot;THE-SUPABASE-URL-STRING-WITH-YOUR-PASSWORD-ADDED&quot;&#39; &gt;&gt; .env</pre><p>Now, the easiest way to interact with this database is through SQLAlchemy. Let’s install it:</p><pre>pip install &quot;sqlalchemy==2.0.35&quot; psycopg2-binary<br>echo &quot;psycopg2-binary\nsqlalchemy==2.0.35\n&quot; &gt;&gt; requirements.txt</pre><blockquote>Note: <a href="https://sqlalchemy.org/">SQLAlchemy</a> is a Python SQL toolkit and Object-Relational Mapping (ORM) library that lets us interact with databases using Python code instead of raw SQL. For our price tracking project, it provides essential features like database connection management, schema definition through Python classes, and efficient querying capabilities. This makes it much easier to store and retrieve product information and price histories in our Postgres database.</blockquote><p>After the installation, create a new database.py file for storing database-related functions:</p><pre>touch database.py</pre><p>Let’s populate this script:</p><pre>from sqlalchemy import create_engine, Column, String, Float, DateTime, ForeignKey<br>from sqlalchemy.orm import sessionmaker, relationship, declarative_base<br>from datetime import datetime<br><br>Base = declarative_base()<br><br><br>class Product(Base):<br>    __tablename__ = &quot;products&quot;<br><br>    url = Column(String, primary_key=True)<br>    prices = relationship(<br>        &quot;PriceHistory&quot;, back_populates=&quot;product&quot;, cascade=&quot;all, delete-orphan&quot;<br>    )<br><br><br>class PriceHistory(Base):<br>    __tablename__ = &quot;price_histories&quot;<br><br>    id = Column(String, primary_key=True)<br>    product_url = Column(String, ForeignKey(&quot;products.url&quot;))<br>    name = Column(String, nullable=False)<br>    price = Column(Float, nullable=False)<br>    currency = Column(String, nullable=False)<br>    main_image_url = Column(String)<br>    timestamp = Column(DateTime, nullable=False)<br>    product = relationship(&quot;Product&quot;, back_populates=&quot;prices&quot;)</pre><p>The code above defines two SQLAlchemy models for our price tracking database:</p><p>The Product model acts as a registry of all items we want to track. It’s kept simple with just the product URL as we don’t want to duplicate data that changes over time.</p><p>The PriceHistory model stores the actual price data points and product details at specific moments in time. This separation allows us to:</p><ul><li>Track how product details (name, price, image) change over time</li><li>Maintain a clean historical record for each product</li><li>Efficiently query price trends without loading unnecessary data</li></ul><p>Each record in PriceHistory contains:</p><ul><li>A unique ID as primary key</li><li>The product URL as a foreign key linking to the Product</li><li>The product name</li><li>The price value and currency</li><li>The main product image URL</li><li>A timestamp of when the price was recorded</li></ul><p>The relationship between Product and PriceHistory is bidirectional, allowing easy navigation between related records. The cascade setting ensures price histories are deleted when their product is deleted.</p><p>These models provide the structure for storing and querying our price tracking data in a PostgreSQL database using SQLAlchemy’s ORM capabilities.</p><p>Now, we define a Database class with a singe add_product method:</p><pre>class Database:<br>    def __init__(self, connection_string):<br>        self.engine = create_engine(connection_string)<br>        Base.metadata.create_all(self.engine)<br>        self.Session = sessionmaker(bind=self.engine)<br><br>    def add_product(self, url):<br>        session = self.Session()<br>        try:<br>            # Create the product entry<br>            product = Product(url=url)<br>            session.merge(product)  # merge will update if exists, insert if not<br>            session.commit()<br>        finally:<br>            session.close()</pre><p>The Database class above provides core functionality for managing product data in our PostgreSQL database. It takes a connection string in its constructor to establish the database connection using SQLAlchemy.</p><p>The add_product method allows us to store new product URLs in the database. It uses SQLAlchemy’s merge functionality which intelligently handles both inserting new products and updating existing ones, preventing duplicate entries.</p><p>The method carefully manages database sessions, ensuring proper resource cleanup by using try/finally blocks. This prevents resource leaks and maintains database connection stability.</p><p>Let’s use this method inside the sidebar of our UI. Switch to ui.py and make the following adjustments:</p><p>First, update the imports to load the Database class and initialize it:</p><pre>import os<br>import streamlit as st<br><br>from utils import is_valid_url<br>from database import Database<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>with st.spinner(&quot;Loading database...&quot;):<br>    db = Database(os.getenv(&quot;POSTGRES_URL&quot;))</pre><p>The code integrates the Database class into the Streamlit UI by importing required dependencies and establishing a database connection. The database URL is loaded securely from environment variables using python-dotenv. The Database class creates or updates the tables we specified in database.py after being initialized.</p><p>The database initialization process is wrapped in a Streamlit spinner component to maintain responsiveness while establishing the connection. This provides visual feedback during the connection setup period, which typically requires a brief initialization time.</p><p>Then, in the sidebar code, we only need to add a single line of code to add the product to the database if the URL is valid:</p><pre># Set up sidebar<br>with st.sidebar:<br>    st.title(&quot;Add New Product&quot;)<br>    product_url = st.text_input(&quot;Product URL&quot;)<br>    add_button = st.button(&quot;Add Product&quot;)<br><br>    if add_button:<br>        if not product_url:<br>            st.error(&quot;Please enter a product URL&quot;)<br>        elif not is_valid_url(product_url):<br>            st.error(&quot;Please enter a valid URL&quot;)<br>        else:<br>            db.add_product(product_url)  # This is the new line<br>            st.success(&quot;Product is now being tracked!&quot;)</pre><p>In the final else block that runs when the product URL is valid, we call the add_product method to store the product in the database.</p><p>Let’s commit everything:</p><pre>git add .<br>git commit -m &quot;Add a Postgres database integration for tracking product URLs&quot;</pre><h4>Step 6: Storing price histories for new products</h4><p>Now, after the product is added to the products table, we want to add its details and its scraped price to the price_histories table.</p><p>First, switch to database.py and add a new method for creating entries in the PriceHistories table:</p><pre>class Database:<br>    ...  # the rest of the class<br><br>    def add_price(self, product_data):<br>        session = self.Session()<br>        try:<br>            price_history = PriceHistory(<br>                id=f&quot;{product_data[&#39;url&#39;]}_{product_data[&#39;timestamp&#39;]}&quot;,<br>                product_url=product_data[&quot;url&quot;],<br>                name=product_data[&quot;name&quot;],<br>                price=product_data[&quot;price&quot;],<br>                currency=product_data[&quot;currency&quot;],<br>                main_image_url=product_data[&quot;main_image_url&quot;],<br>                timestamp=product_data[&quot;timestamp&quot;],<br>            )<br>            session.add(price_history)<br>            session.commit()<br>        finally:<br>            session.close()</pre><p>The add_price method takes a dictionary containing product data (which is returned by our scraper) and creates a new entry in the PriceHistory table. The entry’s ID is generated by combining the product URL with a timestamp. The method stores essential product information like name, price, currency, image URL, and the timestamp of when the price was recorded. It uses SQLAlchemy’s session management to safely commit the new price history entry to the database.</p><p>Now, we need to add this functionality to the sidebar as well. In ui.py, add a new import statement that loads the scrape_product function from scraper.py:</p><pre>...  # The rest of the imports<br>from scraper import scrape_product</pre><p>Then, update the else block in the sidebar again:</p><pre>with st.sidebar:<br>    st.title(&quot;Add New Product&quot;)<br>    product_url = st.text_input(&quot;Product URL&quot;)<br>    add_button = st.button(&quot;Add Product&quot;)<br><br>    if add_button:<br>        if not product_url:<br>            st.error(&quot;Please enter a product URL&quot;)<br>        elif not is_valid_url(product_url):<br>            st.error(&quot;Please enter a valid URL&quot;)<br>        else:<br>            db.add_product(product_url)<br>            with st.spinner(&quot;Added product to database. Scraping product data...&quot;):<br>                product_data = scrape_product(product_url)<br>                db.add_price(product_data)<br>            st.success(&quot;Product is now being tracked!&quot;)</pre><p>Now when a user enters a product URL and clicks the “Add Product” button, several things happen:</p><ol><li>The URL is validated to ensure it’s not empty and is properly formatted.</li><li>If valid, the URL is added to the products table via add_product().</li><li>The product page is scraped immediately to get current price data.</li><li>This initial price data is stored in the price history table via add_price().</li><li>The user sees loading spinners and success messages throughout the process.</li></ol><p>This gives us a complete workflow for adding new products to track, including capturing their initial price point. The UI provides clear feedback at each step and handles errors gracefully.</p><p>Check that everything is working the way we want it and then, commit the new changes:</p><pre>git add .<br>git commit -m &quot;Add a feature to track product prices after they are added&quot;</pre><h4>Step 7: Displaying each product’s price history in the main dashboard</h4><p>Let’s take a look at the final product shown in the introduction once again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NB1V7sWXczJRUiTESmJN9A.png" /></figure><p>Apart from the sidebar, the main dashboard shows each product’s price history visualized with a Plotly line plot where the X axis is the timestamp while the Y axis is the prices. Each line plot is wrapped in a Streamlit component that includes buttons for removing the product from the database or visiting its source URL.</p><p>In this step, we will implement the plotting feature and leave the two buttons for now. First, add a new method to the Database class for retrieving the price history for each product:</p><pre>class Database:<br>    ...  # The rest of the code<br><br>    def get_price_history(self, url):<br>        &quot;&quot;&quot;Get price history for a product&quot;&quot;&quot;<br>        session = self.Session()<br>        try:<br>            return (<br>                session.query(PriceHistory)<br>                .filter(PriceHistory.product_url == url)<br>                .order_by(PriceHistory.timestamp.desc())<br>                .all()<br>            )<br>        finally:<br>            session.close()</pre><p>The method queries the price histories table based on product URL, orders the rows in descending order (oldest first) and returns the results.</p><p>Then, add another method for retrieving all products from the products table:</p><pre>class Database:<br>    ...<br>    <br>    def get_all_products(self):<br>        session = self.Session()<br>        try:<br>            return session.query(Product).all()<br>        finally:<br>            session.close()</pre><p>The idea is that every time our Streamlit app is opened, the main dashboard queries all existing products from the database and render their price histories with line charts in dedicated components.</p><p>To create the line charts, we need Plotly and Pandas, so install them in your environment:</p><pre>pip install pandas plotly<br>echo &quot;pandas\nplotly\n&quot; &gt;&gt; requirements.txt</pre><p>Afterward, import them at the top of ui.py along with other existing imports:</p><pre>import pandas as pd<br>import plotly.express as px</pre><p>Then, switch to ui.py and paste the following snippet of code after the Main content section:</p><pre># Main content<br>st.title(&quot;Price Tracker Dashboard&quot;)<br>st.markdown(&quot;## Tracked Products&quot;)<br><br># Get all products<br>products = db.get_all_products()</pre><p>Here, after the page title and subtitle is shown, we are retrieving all products from the database. Let’s loop over them:</p><pre># Create a card for each product<br>for product in products:<br>    price_history = db.get_price_history(product.url)<br>    if price_history:<br>        # Create DataFrame for plotting<br>        df = pd.DataFrame(<br>            [<br>                {&quot;timestamp&quot;: ph.timestamp, &quot;price&quot;: ph.price, &quot;name&quot;: ph.name}<br>                for ph in price_history<br>            ]<br>        )</pre><p>For each product, we get their price history with db.get_price_history and then, convert this data into a dataframe with three columns:</p><ul><li>Timestamp</li><li>Price</li><li>Product name</li></ul><p>This makes plotting easier with Plotly. Next, we create a Streamlit expander component for each product:</p><pre># Create a card for each product<br>for product in products:<br>    price_history = db.get_price_history(product.url)<br>    if price_history:<br>        ...<br>        # Create a card-like container for each product<br>        with st.expander(df[&quot;name&quot;][0], expanded=False):<br>            st.markdown(&quot;---&quot;)<br>            col1, col2 = st.columns([1, 3])<br><br>            with col1:<br>                if price_history[0].main_image_url:<br>                    st.image(price_history[0].main_image_url, width=200)<br>                st.metric(<br>                    label=&quot;Current Price&quot;,<br>                    value=f&quot;{price_history[0].price} {price_history[0].currency}&quot;,<br>                )</pre><p>The expander shows the product name as its title and contains:</p><ol><li>A divider line</li><li>Two columns:</li></ol><ul><li>Left column: Product image (if available) and current price metric</li><li>Right column (shown in next section)</li></ul><p>The price is displayed using Streamlit’s metric component which shows the current price and currency.</p><p>Here is the rest of the code:</p><pre>...<br>            <br>            with col2:<br>                # Create price history plot<br>                fig = px.line(<br>                    df,<br>                    x=&quot;timestamp&quot;,<br>                    y=&quot;price&quot;,<br>                    title=None,<br>                )<br>                fig.update_layout(<br>                    xaxis_title=None,<br>                    yaxis_title=&quot;Price&quot;,<br>                    showlegend=False,<br>                    margin=dict(l=0, r=0, t=0, b=0),<br>                    height=300,<br>                )<br>                fig.update_xaxes(tickformat=&quot;%Y-%m-%d %H:%M&quot;, tickangle=45)<br>                fig.update_yaxes(tickprefix=f&quot;{price_history[0].currency} &quot;, tickformat=&quot;.2f&quot;)<br>                st.plotly_chart(fig, use_container_width=True)</pre><p>In the right column, we create an interactive line plot using Plotly Express to visualize the price history over time. The plot shows price on the y-axis and timestamp on the x-axis. The layout is customized to remove the title, adjust axis labels and formatting, and optimize the display size. The timestamps are formatted to show date and time, with angled labels for better readability. Prices are displayed with 2 decimal places and a dollar sign prefix. The plot is rendered using Streamlit’s plotly_chart component and automatically adjusts its width to fill the container.</p><p>After this step, the UI must be fully functional and ready to track products. For example, here is what mine looks like after adding a couple of products:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CBZ_xAA9jdluWc_1.png" /></figure><p>But notice how the price history chart doesn’t show anything. That’s because we haven’t populated it by checking the product price in regular intervals. Let’s do that in the next couple of steps. For now, commit the latest changes we’ve made:</p><pre>git add .<br>git commit -m &quot;Display product price histories for each product in the dashboard&quot;</pre><p>Let’s take a brief moment to summarize the steps we took so far and what’s next. So far, we’ve built a Streamlit interface that allows users to add product URLs and displays their current prices and basic information. We’ve implemented the database schema, created functions to scrape product data, and designed a clean UI with price history visualization. The next step is to set up automated price checking to populate our history charts and enable proper price tracking over time.</p><h4>Step 8: Adding new price entries for existing products</h4><p>Now, we want to write a script that adds new price entries in the price_histories table for each product in products table. We call this script check_prices.py:</p><pre># check_prices.py<br>import os<br>from database import Database<br>from dotenv import load_dotenv<br>from firecrawl import FirecrawlApp<br>from scraper import scrape_product<br><br>load_dotenv()<br><br>db = Database(os.getenv(&quot;POSTGRES_URL&quot;))<br>app = FirecrawlApp()</pre><p>At the top, we are importing the functions and packages and initializing the database and a Firecrawl app. Then, we define a simple check_prices function:</p><pre>def check_prices():<br>    products = db.get_all_products()<br><br>    for product in products:<br>        try:<br>            updated_product = scrape_product(product.url)<br>            db.add_price(updated_product)<br>            print(f&quot;Added new price entry for {updated_product[&#39;name&#39;]}&quot;)<br>        except Exception as e:<br>            print(f&quot;Error processing {product.url}: {e}&quot;)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    check_prices()</pre><p>In the function body, we retrieve all products URLs, retrieve their new price data with scrape_product function from scraper.py and then, add a new price entry for the product with db.add_price.</p><p>If you run the function once and refresh the Streamlit app, you must see a line chart appear for each product you are tracking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jZ1IaGyzk4_wNwoy.png" /></figure><p>Let’s commit the changes in this step:</p><pre>git add .<br>git commit -m &quot;Add a script for checking prices of existing products&quot;</pre><p>So, in a nutshell, if we want to fetch a new price for existing products in our database, we run the check_prices.py script.</p><h4>Step 9: Check prices regularly with GitHub Actions</h4><p>GitHub Actions is a continuous integration and continuous delivery (CI/CD) platform that allows you to automate various software workflows directly from your GitHub repository. In our case, it’s particularly useful because we can set up automated price checks to run the check_prices.py script at regular intervals (e.g., daily or hourly) without manual intervention. This ensures we consistently track price changes and maintain an up-to-date database of historical prices for our tracked products.</p><p>So, the first step is creating a new GitHub repository for our project and pushing existing code to it:</p><pre>git remote add origin https://github.com/yourusername/price-tracker.git<br>git push origin main</pre><p>Then, return to your terminal and create this directory structure:</p><pre>mkdir -p .github/workflows<br>touch .github/workflows/check_prices.yml</pre><p>The first command creates a new directory structure .github/workflows using the -p flag to create parent directories if they don’t exist.</p><p>The second command creates an empty YAML file called check_prices.yml inside the workflows directory. GitHub Actions looks for workflow files in this specific location - any YAML files in the .github/workflows directory will be automatically detected and processed as workflow configurations.</p><p>These YAML files define when and how your automated tasks should run, what environment they need, and what commands to execute. In our case, this file will contain instructions for GitHub Actions to periodically run our price-checking script. Let’s write it:</p><pre>name: Price Check<br><br>on:<br>  schedule:<br>    # Runs every 3 minutes<br>    - cron: &quot;*/3 * * * *&quot;<br>  workflow_dispatch: # Allows manual triggering</pre><p>Let’s break down this first part of the YAML file:</p><p>The name: Price Check line gives our workflow a descriptive name that will appear in the GitHub Actions interface.</p><p>The on: section defines when this workflow should be triggered. We’ve configured two triggers:</p><ol><li>A schedule using cron syntax */3 * * * * which runs the workflow every 3 minutes. The five asterisks represent minute, hour, day of month, month, and day of week respectively. The */3 means “every 3rd minute”. The 3-minute interval is for debugging purposes, we will need to choose a wider interval later on to respect the free limits of GitHub actions.</li><li>workflow_dispatch enables manual triggering of the workflow through the GitHub Actions UI, which is useful for testing or running the check on-demand.</li></ol><p>Now, let’s add the rest:</p><pre>jobs:<br>  check-prices:<br>    runs-on: ubuntu-latest<br><br>    steps:<br>      - name: Checkout code<br>        uses: actions/checkout@v4<br><br>      - name: Set up Python<br>        uses: actions/setup-python@v5<br>        with:<br>          python-version: &quot;3.10&quot;<br>          cache: &quot;pip&quot;<br><br>      - name: Install dependencies<br>        run: |<br>          python -m pip install --upgrade pip<br>          pip install -r requirements.txt<br><br>      - name: Run price checker<br>        env:<br>          FIRECRAWL_API_KEY: ${{ secrets.FIRECRAWL_API_KEY }}<br>          POSTGRES_URL: ${{ secrets.POSTGRES_URL }}<br>        run: python check_prices.py</pre><p>Let’s break down this second part of the YAML file:</p><p>The jobs: section defines the actual work to be performed. We have one job named check-prices that runs on an Ubuntu virtual machine (runs-on: ubuntu-latest).</p><p>Under steps:, we define the sequence of actions:</p><ol><li>First, we checkout our repository code using the standard actions/checkout@v4 action</li><li>Then we set up Python 3.10 using actions/setup-python@v5, enabling pip caching to speed up dependency installation</li><li>Next, we install our Python dependencies by upgrading pip and installing requirements from our requirements.txt file. At this point, it is essential that you were keeping a complete dependency file based on the installs we made in the project.</li><li>Finally, we run our price checker script, providing two environment variables:</li></ol><ul><li>FIRECRAWL_API_KEY: For accessing the web scraping service</li><li>POSTGRES_URL: For connecting to our database</li></ul><p>Both variables must be stored in our GitHub repository as secrets for this workflow file to run without errors. So, navigate to the repository you’ve created for the project and open its Settings. Under “Secrets and variables” &gt; “Actions”, click on “New repository secret” button to add the environment variables we have in the .env file one-by-one.</p><p>Then, return to your terminal, commit the changes and push:</p><pre>git add . <br>git commit -m &quot;Add a workflow to check prices regularly&quot;<br>git push origin main</pre><p>Next, navigate to your GitHub repository again and click on the “Actions” tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nuTyAPporRvbxqbh.png" /></figure><p>From there, you can run the workflow manually (click “Run workflow” and refresh the page). If it is executed successfully, you can return to the Streamlit app and refresh to see the new price added to the chart.</p><h4>Step 10: Setting up Discord for notifications</h4><p>Now that we know our scheduling workflow works, the first order of business is setting a wider check interval in the workflow file. Even though our first workflow was runmanually, the rest runs automatically.</p><pre># Change this part of the workflow file<br>on:<br>  schedule:<br>    # Runs every 6 hours<br>    - cron: &quot;0 0,6,12,18 * * *&quot;<br>  workflow_dispatch: # Allows manual triggering</pre><p>The cron syntax 0 0,6,12,18 * * * can be broken down as follows:</p><ul><li>First 0: Run at minute 0</li><li>0,6,12,18: Run at hours 0 (midnight), 6 AM, 12 PM (noon), and 6 PM</li><li>First *: Run every day of the month</li><li>Second *: Run every month</li><li>Third *: Run every day of the week</li></ul><p>So this schedule will check prices four times daily: at midnight, 6 AM, noon, and 6 PM (UTC time). This spacing helps stay within GitHub Actions’ free tier limits while still catching most price changes.</p><p>Now, commit and push the changes:</p><pre>git add .<br>git commit -m &quot;Set a wider check interval in the workflow file&quot;<br>git push origin main</pre><p>Now comes the interesting part. Each time the workflow is run, we want to compare the current price of the product to its original price when we started tracking it. If the difference between these two prices exceeds a certain threshold like 5%, this means there is a discount happening for the product and we want to send a notification.</p><p>The easiest way to set this up is by using Discord webhooks. So, if you don’t have one already, go to Discord.com and create a new account (optionally, download the desktop app as well). Then, setting up Discord notifications requires a few careful steps:</p><ol><li>Create a Discord server:</li></ol><ul><li>Click the ”+” button in the bottom-left corner of Discord</li><li>Choose “Create My Own” → “For me and my friends”</li><li>Give your server a name (e.g., “Price Alerts”)</li></ul><p>2. Create a channel for alerts:</p><ul><li>Your server comes with a #general channel by default</li><li>You can use this or create a new channel called #price-alerts</li><li>Right-click the channel you want to use</li></ul><p>3. Set up the webhook</p><ul><li>Select “Edit Channel” from the right-click menu</li><li>Go to the “Integrations” tab</li><li>Click “Create Webhook”</li><li>Give it a name like “Price Alert Bot”</li><li>The webhook URL will be generated automatically</li><li>Click “Copy Webhook URL” - this is your unique notification endpoint</li></ul><p>4. Secure the webhook URL</p><ul><li>Never share or commit your webhook URL directly</li><li>Add it to your .env file as DISCORD_WEBHOOK_URL</li><li>Add it to your GitHub repository secrets</li><li>The URL should look something like: https://discord.com/api/webhooks/...</li></ul><p>This webhook will serve as a secure endpoint that our price tracker can use to send notifications directly to your Discord channel.</p><p>Webhooks are automated messages sent from apps to other apps in real-time. They work like a notification system - when something happens in one app, it automatically sends data to another app through a unique URL. In our case, we’ll use Discord webhooks to automatically notify us when there’s a price drop. Whenever our price tracking script detects a significant discount, it will send a message to our Discord channel through the webhook URL, ensuring we never miss a good deal.</p><p>After copying the webhook URL, you should save it as environment variable to your .env file:</p><pre>echo &quot;DISCORD_WEBHOOK_URL=&#39;THE-URL-YOU-COPIED&#39;&quot; &gt;&gt; .env</pre><p>Now, create a new file called notifications.py and paste the following contents:</p><pre>from dotenv import load_dotenv<br>import os<br>import aiohttp<br>import asyncio<br><br>load_dotenv()<br><br><br>async def send_price_alert(<br>    product_name: str, old_price: float, new_price: float, url: str<br>):<br>    &quot;&quot;&quot;Send a price drop alert to Discord&quot;&quot;&quot;<br>    drop_percentage = ((old_price - new_price) / old_price) * 100<br><br>    message = {<br>        &quot;embeds&quot;: [<br>            {<br>                &quot;title&quot;: &quot;Price Drop Alert! 🎉&quot;,<br>                &quot;description&quot;: f&quot;**{product_name}**\nPrice dropped by {drop_percentage:.1f}%!\n&quot;<br>                f&quot;Old price: ${old_price:.2f}\n&quot;<br>                f&quot;New price: ${new_price:.2f}\n&quot;<br>                f&quot;[View Product]({url})&quot;,<br>                &quot;color&quot;: 3066993,<br>            }<br>        ]<br>    }<br><br>    try:<br>        async with aiohttp.ClientSession() as session:<br>            await session.post(os.getenv(&quot;DISCORD_WEBHOOK_URL&quot;), json=message)<br>    except Exception as e:<br>        print(f&quot;Error sending Discord notification: {e}&quot;)</pre><p>The send_price_alert function above is responsible for sending price drop notifications to Discord using webhooks. Let’s break down what’s new:</p><ol><li>The function takes 4 parameters:</li></ol><ul><li>product_name: The name of the product that dropped in price</li><li>old_price: The previous price before the drop</li><li>new_price: The current lower price</li><li>url: Link to view the product</li></ul><p>2. It calculates the percentage drop in price using the formula: ((old_price - new_price) / old_price) * 100</p><p>3. The notification is formatted as a Discord embed - a rich message format that includes:</p><ul><li>A title with a celebration emoji</li><li>A description showing the product name, price drop percentage, old and new prices</li><li>A link to view the product</li><li>A green color (3066993 in decimal)</li></ul><p>4. The message is sent asynchronously using aiohttp to post to the Discord webhook URL stored in the environment variables</p><p>5. Error handling is included to catch and print any issues that occur during the HTTP request</p><p>This provides a clean way to notify users through Discord whenever we detect a price drop for tracked products.</p><p>To check if the notification system works, add this main block to the end of the script:</p><pre>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(send_price_alert(&quot;Test Product&quot;, 100, 90, &quot;https://www.google.com&quot;))</pre><p>asyncio.run() is used here because send_price_alert is an async function that needs to be executed in an event loop. asyncio.run() creates and manages this event loop, allowing the async HTTP request to be made properly. Without it, we wouldn’t be able to use the await keyword inside send_price_alert.</p><p>To run the script, install aiohttp:</p><pre>pip install aiohttp<br>echo &quot;aiohttp\n&quot; &gt;&gt; requirements.txt<br># Run the script<br>python notifications.py</pre><p>If all is well, you should get a Discord message in your server that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/0*GhJXsJdybnWo900r.png" /></figure><p>Let’s commit the changes we have:</p><pre>git add .<br>git commit -m &quot;Set up Discord alert system&quot;</pre><p>Also, don’t forget to add the Discord webhook URL to your GitHub repository secrets!</p><h4>Step 11: Sending Discord alerts when prices drop</h4><p>Now, the only step left is adding a price comparison logic to check_prices.py. In other words, we want to use the send_price_alert function if the new scraped price is lower than the original. This requires a revamped check_prices.py script:</p><pre># Rewriting check_prices.py<br>import os<br>import asyncio<br>from database import Database<br>from dotenv import load_dotenv<br>from firecrawl import FirecrawlApp<br>from scraper import scrape_product<br>from notifications import send_price_alert<br><br>load_dotenv()<br>db = Database(os.getenv(&quot;POSTGRES_URL&quot;))<br>app = FirecrawlApp()<br># Threshold percentage for price drop alerts (e.g., 5% = 0.05)<br>PRICE_DROP_THRESHOLD = 0.05<br><br>async def check_prices():<br>    products = db.get_all_products()<br>    product_urls = set(product.url for product in products)<br>    for product_url in product_urls:<br>        # Get the price history<br>        price_history = db.get_price_history(product_url)<br>        if not price_history:<br>            continue<br>        # Get the earliest recorded price<br>        earliest_price = price_history[-1].price<br>        # Retrieve updated product data<br>        updated_product = scrape_product(product_url)<br>        current_price = updated_product[&quot;price&quot;]<br>        # Add the price to the database<br>        db.add_price(updated_product)<br>        print(f&quot;Added new price entry for {updated_product[&#39;name&#39;]}&quot;)<br>        # Check if price dropped below threshold<br>        if earliest_price &gt; 0:  # Avoid division by zero<br>            price_drop = (earliest_price - current_price) / earliest_price<br>            if price_drop &gt;= PRICE_DROP_THRESHOLD:<br>                await send_price_alert(<br>                    updated_product[&quot;name&quot;], earliest_price, current_price, product_url<br>                )<br><br>if __name__ == &quot;__main__&quot;:<br>    asyncio.run(check_prices())</pre><p>Let’s examine the key changes in this enhanced version of check_prices.py:</p><ol><li>New imports and setup:</li></ol><ul><li>Added asyncio for async/await support</li><li>Imported send_price_alert from notifications.py</li><li>Defined PRICE_DROP_THRESHOLD = 0.05 (5% threshold for alerts)</li></ul><p>2. Async function conversion:</p><ul><li>Converted check_prices() to async function</li><li>Gets unique product URLs using set comprehension to avoid duplicates</li></ul><p>3. Price history analysis:</p><ul><li>Retrieves full price history for each product</li><li>Gets earliest_price from history[-1] (works because we ordered by timestamp DESC)</li><li>Skips products with no price history using continue</li></ul><p>4. Price drop detection logic:</p><ul><li>Calculates drop percentage: (earliest_price - current_price) / earliest_price</li><li>Checks if drop exceeds 5% threshold</li><li>Sends Discord alert if threshold exceeded using await send_price_alert()</li></ul><p>5. Async main block:</p><ul><li>Uses asyncio.run() to execute async check_prices() in event loop</li></ul><p>When I tested this new version of the script, I immediately got an alert:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*FQHkwRcbz8v8cAl2.png" /></figure><p>Before we supercharge our workflow with the new notification system, you should add this line of code to your check_prices.yml workflow file to read the Discord webhook URL from your GitHub secrets:</p><pre>...<br>    - name: Run price checker<br>        env:<br>          FIRECRAWL_API_KEY: ${{ secrets.FIRECRAWL_API_KEY }}<br>          POSTGRES_URL: ${{ secrets.POSTGRES_URL }}<br>          DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}<br>        run: python automated_price_tracking/check_prices.py</pre><p>Finally, let’s commit everything and push to GitHub so that our workflow is supercharged with our notification system:</p><pre>git add .<br>git commit -m &quot;Add notification system to price drops&quot;<br>git push origin main</pre><h3>Limitations of Free Tier Tools Used in the Tutorial</h3><p>Before wrapping up, let’s quickly review the limitations of the free tools we used in this tutorial:</p><ul><li>GitHub Actions: Limited to 2,000 minutes per month for free accounts. Consider increasing the cron interval to stay within limits.</li><li>Supabase: Free tier includes 500MB database storage and limited row count. Monitor usage if tracking many products.</li><li>Firecrawl: The free API tier allows 500 requests per month. This means that at 6 hour intervals, you can track up to four products in the free plan.</li><li>Streamlit Cloud: Free hosting tier has some memory/compute restrictions and goes to sleep after inactivity.</li></ul><p>While these limitations exist, they’re quite generous for personal use and learning. The app will work well for tracking a reasonable number of products with daily price checks.</p><h3>Conclusion and Next Steps</h3><p>Congratulations for making it to the end of this extremely long tutorial! We’ve just covered how to implement an end-to-end Python project you can proudly showcase on your portfolio. We built a complete price tracking system that scrapes product data from e-commerce websites, stores it in a Postgres database, analyzes price histories, and sends automated Discord notifications when prices drop significantly.</p><p>Along the way, we learned about web scraping with Firecrawl, database management with SQLAlchemy, asynchronous programming with asyncio, building interactive UIs with Streamlit, automating with GitHub Actions and integrating external webhooks.</p><p>However, the project is far from perfect. Since we took a top-down approach to building this app, our project code is scattered across multiple files and often doesn’t follow programming best practices. For this reason, I’ve recreated the same project in a much more sophisticated manner with production-level features.</p><p><a href="https://github.com/BexTuychiev/automated-price-tracking">This new version on GitHub</a> implements proper database session management, faster operations and overall smoother user experience. Also, this version includes buttons for removing products from the database and visiting them through the app.</p><p>If you decide to stick with the basic version, you can find <a href="https://github.com/mendableai/firecrawl-app-examples/tree/main/automated_price_tracking">the full project code and notebook</a> in the official Firecrawl GitHub repository’s example projects. I also recommend that you deploy your Streamlit app to <a href="http://share.streamlit.io">Streamlit Cloud</a> so that you have a functional app accessible everywhere you go.</p><p>Here are some further improvements you might consider for the app:</p><ul><li>Improve the price comparison logic: the app compares the current price to the oldest recorded price, which might not be ideal. You may want to compare against recent price trends instead.</li><li>No handling of currency conversion if products use different currencies.</li><li>The Discord notification system doesn’t handle rate limits or potential webhook failures gracefully.</li><li>No error handling for Firecrawl scraper — what happens if the scraping fails?</li><li>No consistent usage of logging to help track issues in production.</li><li>No input URL sanitization before scraping.</li></ul><p>Some of these features are implemented in <a href="https://github.com/BexTuychiev/automated-price-tracking">the advanced version of the project</a>, so definitely check it out!</p><p>Here are some more guides from me if you are interested:</p><ul><li><a href="https://www.firecrawl.dev/blog/automated-web-scraping-free-2025">How to Run Web Scrapers on Schedule</a></li><li><a href="https://www.firecrawl.dev/blog/mastering-firecrawl-scrape-endpoint">More about using Firecrawl’s </a><a href="https://www.firecrawl.dev/blog/mastering-firecrawl-scrape-endpoint">scrape_url function</a></li><li><a href="https://www.firecrawl.dev/blog/mastering-the-crawl-endpoint-in-firecrawl">Scraping entire websites with Firecrawl in a single command — the /crawl endpoint</a></li></ul><p>Thank you for reading!</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3906b1aaed1" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/end-to-end-portfolio-project-building-amazon-price-tracker-in-python-d3906b1aaed1">End-to-end Portfolio Project: Building Amazon Price Tracker in Python</a> was originally published in <a href="https://medium.datadriveninvestor.com">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firecrawl: Scrape Any Website Using AI and Bypass Blockers in Python]]></title>
            <link>https://medium.datadriveninvestor.com/firecrawl-scrape-any-website-using-ai-and-bypass-blockers-in-python-553e16fa8b5a?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/553e16fa8b5a</guid>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 16:18:48 GMT</pubDate>
            <atom:updated>2024-12-10T06:20:53.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Firecrawl: Scrape Any Website Using AI and Bypass Blockers</h3><h4>And get clean, LLM-ready data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rq2UcwEWFPFn_dqWNb1S-g.png" /><figcaption>Image by the author via Leonardo AI</figcaption></figure><h3>Getting Started with Modern Web Scraping: An Introduction</h3><p>Traditional web scraping offers unique challenges. Relevant information is often scattered across multiple pages containing complex elements like code blocks, iframes, and media. JavaScript-heavy websites and authentication requirements add additional complexity to the scraping process.</p><p>Even after successfully scraping, the content requires specific formatting to be useful for downstream processes like data engineering or training AI and machine learning models.</p><p>Firecrawl addresses these challenges by providing a specialized scraping solution. Its <a href="https://docs.firecrawl.dev/features/scrape">/scrape endpoint</a> offers features like JavaScript rendering, automatic content extraction, bypassing blockers, and flexible output formats, making collecting high-quality information and training data at scale easier.</p><p>In this guide, we’ll explore how to effectively use Firecrawl’s /scrape endpoint to extract structured data from static and dynamic websites. We’ll start with a basic scraping setup and then dive into a real-world example of scraping weather data from weather.com, demonstrating how to handle JavaScript-based scraper actions, extract structured data using schemas, and capture screenshots during the scraping process.</p><h3>Table of Contents</h3><ul><li>Getting Started with Modern Web Scraping: An Introduction</li><li>What Is Firecrawl’s /scrape Endpoint? The Short Answer</li><li>Prerequisites: Setting Up Firecrawl</li><li>Basic Scraping Setup</li><li>Large-scale Scraping With Batch Operations</li><li>Batch Scraping with batch_scrape_urls</li><li>Asynchronous batch scraping with async_batch_scrape_urls</li><li>How to Scrape Dynamic JavaScript Websites</li><li>Conclusion</li></ul><h3>What Is Firecrawl’s /scrape Endpoint? The Short Answer</h3><p>The /scrape endpoint is Firecrawl’s core web scraping API that enables automated extraction of content from any webpage. It handles common web scraping challenges like:</p><ul><li>JavaScript rendering — Executes JavaScript to capture dynamically loaded content</li><li>Content extraction — Automatically identifies and extracts main content while filtering out noise</li><li>Format conversion — Converts HTML to clean formats like Markdown or structured JSON</li><li>Screenshot capture — Takes full or partial page screenshots during scraping</li><li>Browser automation — Supports clicking, typing, and other browser interactions</li><li>Anti-bot bypass — Uses rotating proxies and browser fingerprinting to avoid blocks</li></ul><p>The endpoint accepts a URL and configuration parameters and returns the scraped content in your desired format. It’s designed to be flexible enough for simple static page scraping and complex dynamic site automation.</p><p>Now that we understand what the endpoint does at a high level, let’s look at how to set it up and use it in practice.</p><h3>Prerequisites: Setting Up Firecrawl</h3><p>Firecrawl’s scraping engine is exposed as a REST API, so you can use command-line tools like cURL to use it. However, for a more comfortable experience, better flexibility, and control, I recommend using one of its SDKs for Python, Node, Rust, or Go. This tutorial will focus on the Python version.</p><p>To get started, please make sure to:</p><ol><li>Sign up at <a href="https://www.firecrawl.dev/blog/firecrawl.dev">firecrawl.dev</a>.</li><li>Choose a plan (the free one will work fine for this tutorial).</li></ol><p>Once you sign up, you will be given an API token which you can copy from your <a href="https://www.firecrawl.dev/app">dashboard</a>. The best way to save your key is by using a .env file, ideal for this article:</p><pre>touch .env<br>echo &quot;FIRECRAWL_API_KEY=&#39;YOUR_API_KEY&#39;&quot; &gt;&gt; .env</pre><p>Now, let’s install Firecrawl Python SDK, python-dotenv to read .env files, and Pandas for data analysis later:</p><pre>pip install firecrawl-py python-dotenv pandas</pre><h4>Basic Scraping Setup</h4><p>Scraping with Firecrawl starts by creating an instance of the FirecrawlApp class:</p><pre>from firecrawl import FirecrawlApp<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>app = FirecrawlApp()</pre><p>When you use the load_dotenv() function, the app can automatically use your loaded API key to establish a connection with the scraping engine. Then, scraping any URL takes a single line of code:</p><pre>url = &quot;https://arxiv.org&quot;<br>data = app.scrape_url(url)</pre><p>Let’s take a look at the response format returned by scrape_url method:</p><pre>data[&#39;metadata&#39;]</pre><pre>{<br>    &quot;title&quot;: &#39;arXiv.org e-Print archiveopen searchopen navigation menucontact arXivsubscribe to arXiv mailings&#39;,<br>    &quot;language&quot;: &quot;en&quot;,<br>    &quot;ogLocaleAlternate&quot;: [],<br>    &quot;viewport&quot;: &quot;width=device-width, initial-scale=1&quot;,<br>    &quot;msapplication-TileColor&quot;: &quot;#da532c&quot;,<br>    &quot;theme-color&quot;: &quot;#ffffff&quot;,<br>    &quot;sourceURL&quot;: &quot;&lt;https://arxiv.org&gt;&quot;,<br>    &quot;url&quot;: &quot;&lt;https://arxiv.org/&gt;&quot;,<br>    &quot;statusCode&quot;: 200<br>}</pre><p>The response metadata includes basic information like the page title, viewport settings, and a status code.</p><p>Now, let’s look at the scraped contents, which are converted into markdown by default:</p><pre>from IPython.display import Markdown<br><br>Markdown(data[&#39;markdown&#39;][:500])</pre><pre>arXiv is a free distribution service and an open-access archive for nearly 2.4 million<br>scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics.<br>Materials on this site are not peer-reviewed by arXiv.</pre><p>The response can include several other formats that we can request when scraping a URL. Let’s try requesting multiple formats at once to see what additional data we can get back:</p><pre>data = app.scrape_url(<br>    url, <br>    params={<br>        &#39;formats&#39;: [<br>            &#39;html&#39;, <br>            &#39;rawHtml&#39;, <br>            &#39;links&#39;, <br>            &#39;screenshot&#39;,<br>        ]<br>    }<br>)</pre><p>Here is what these formats scrape:</p><ul><li>HTML: The raw HTML content of the page.</li><li>rawHtml: The unprocessed HTML content, exactly as it appears on the page.</li><li>links: A list of all the hyperlinks found on the page.</li><li>screenshot: An image capture of the page as it appears in a browser.</li></ul><p>The HTML format is useful for developers who need to analyze or manipulate the raw structure of a webpage. The rawHtml format is ideal for cases where the exact original HTML content is required, such as for archival purposes or detailed comparison. The links format is beneficial for SEO specialists and web crawlers who need to extract and analyze all hyperlinks on a page. The screenshot format is perfect for visual documentation, quality assurance, and capturing the appearance of a webpage at a specific point in time.</p><p>Passing more than one scraping format to params adds additional keys to the response:</p><pre>data.keys()</pre><pre>dict_keys([&#39;rawHtml&#39;, &#39;screenshot&#39;, &#39;metadata&#39;, &#39;html&#39;, &#39;links&#39;])</pre><p>Let’s display the screenshot Firecrawl took of arXiv.org:</p><pre>from IPython.display import Image<br><br>Image(data[&#39;screenshot&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0qMETGiI0QwMn-WX.png" /></figure><p>Notice how the screenshot is cropped to fit a certain viewport. For most pages, it is better to capture the entire screen by using the screenshot@fullPage format:</p><pre>data = app.scrape_url(<br>    url,<br>    params={<br>        &quot;formats&quot;: [<br>            &quot;screenshot@fullPage&quot;,<br>        ]<br>    }<br>)<br><br>Image(data[&#39;screenshot&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zaT_u8zI7u6xoyJ6.png" /></figure><p>As a bonus, the /scrape endpoint can handle PDF links as well:</p><pre>pdf_link = &quot;https://arxiv.org/pdf/2411.09833.pdf&quot;<br>data = app.scrape_url(pdf_link)<br><br>Markdown(data[&#39;markdown&#39;][:500])</pre><pre>arXiv:2411.09833v1 \[math.DG\] 14 Nov 2024<br>EINSTEIN METRICS ON THE FULL FLAG F(N).<br>MIKHAIL R. GUZMAN<br>Abstract.LetM=G/Kbe a full flag manifold. In this work, we investigate theG-<br>stability of Einstein metrics onMand analyze their stability types, including coindices,<br>for several cases. We specifically focus onF(n) = SU(n)/T, emphasizingn= 5, where<br>we identify four new Einstein metrics in addition to known ones. Stability data, including<br>coindex and Hessian spectrum, confirms that these metrics on</pre><h3>Further Scrape Configuration Options</h3><p>By default, scrape_url converts everything it sees on a webpage to one of the specified formats. To control this behavior, Firecrawl offers the following parameters:</p><ul><li>onlyMainContent</li><li>includeTags</li><li>excludeTags</li></ul><p>onlyMainContent excludes the navigation, footers, headers, etc., and is set to True by default.</p><p>includeTags and excludeTags can be used to whitelist/blacklist certain HTML elements:</p><pre>url = &quot;https://arxiv.org&quot;<br><br>data = app.scrape_url(url, params={&quot;includeTags&quot;: [&quot;p&quot;], &quot;excludeTags&quot;: [&quot;span&quot;]})<br>Markdown(data[&#39;markdown&#39;][:1000])</pre><pre>[Help](https://info.arxiv.org/help) \| [Advanced Search](https://arxiv.org/search/advanced)<br><br>arXiv is a free distribution service and an open-access archive for nearly 2.4 million<br>scholarly articles in the fields of physics, mathematics, computer science, quantitative biology, quantitative finance, statistics, electrical engineering and systems science, and economics.<br>Materials on this site are not peer-reviewed by arXiv.<br><br>...</pre><p>includeTags and excludeTags also support referring to HTML elements by their #id or .class-name.</p><p>These configuration options help ensure efficient and precise scraping. While onlyMainContent filters out peripheral elements, includeTags and excludeTags enable surgical targeting of specific HTML elements - particularly valuable when dealing with complex webpage structures or when only certain content types are needed.</p><h3>Advanced Data Extraction: Structured Techniques</h3><p>Scraping clean, LLM-ready data is the core philosophy of Firecrawl. However, certain web pages with their complex structures can interfere with this philosophy when scraped in their entirety. For this reason, Firecrawl offers two scraping methods for better-structured outputs:</p><ol><li>Natural language extraction — Use prompts to extract specific information and have an LLM structure the response</li><li>Manual structured data extraction — Define JSON schemas to have an LLM scrape data in a predefined format</li></ol><p>In this section, we will cover both methods.</p><h4>Natural Language Extraction — Use AI to Extract Data</h4><p>To illustrate natural language scraping, let’s try extracting all news article links that may be related to the 2024 US presidential election from the New York Times:</p><pre>url = &quot;https://nytimes.com&quot;</pre><pre>data = app.scrape_url(<br>    url,<br>    params={<br>        &#39;formats&#39;: [&#39;markdown&#39;, &#39;extract&#39;, &#39;screenshot&#39;],<br>        &#39;extract&#39;: {<br>            &#39;prompt&#39;: &quot;Return a list of links of news articles that may be about the 2024 US presidential election&quot;<br>        }<br>    }<br>)</pre><p>To enable this feature, you are required to pass the extract option to the list of formats and provide a prompt in a dictionary to a separate extract field.</p><p>Once scraping finishes, the response will include a new extract key:</p><pre>data[&#39;extract&#39;]</pre><pre>{&#39;news_articles&#39;: [{&#39;title&#39;: &#39;Harris Loss Has Democrats Fighting Over How to Talk About Transgender Rights&#39;,<br>       &#39;link&#39;: &#39;https://www.nytimes.com/2024/11/20/us/politics/presidential-campaign-transgender-rights.html&#39;},<br>      {&#39;title&#39;: &#39;As Democrats Question How to Win Back Latinos, Ruben Gallego Offers Answers&#39;,<br>       &#39;link&#39;: &#39;https://www.nytimes.com/2024/11/20/us/politics/ruben-gallego-arizona-latino-voters-democrats.html&#39;},<br>      ...<br>      {&#39;title&#39;: &#39;The Final Push for Ukraine?&#39;,<br>       &#39;link&#39;: &#39;https://www.nytimes.com/2024/11/20/briefing/ukraine-russia-trump.html&#39;}]}</pre><p>Due to the nature of this scraping method, the returned output can have an arbitrary structure as we can see above. It seems the above output has the following format:</p><pre>{<br>    &quot;news_articles&quot;: [<br>        {&quot;title&quot;: &quot;article_title&quot;, &quot;link&quot;: &quot;article_url&quot;},<br>        ...<br>    ]<br>}</pre><p>This LLM-based extraction can have endless applications, from extracting specific data points from complex websites to analyzing sentiment across multiple news sources to gathering structured information from unstructured web content.</p><p>To improve the accuracy of the extraction and give additional instructions, you have the option to include a system prompt to the underlying LLM:</p><pre>data = app.scrape_url(<br>    url,<br>    params={<br>        &#39;formats&#39;: [&#39;markdown&#39;, &#39;extract&#39;],<br>        &#39;extract&#39;: {<br>            &#39;prompt&#39;: &quot;Find any mentions of specific dollar amounts or financial figures and return them with their context and article link.&quot;,<br>            &#39;systemPrompt&#39;: &quot;You are a helpful assistant that extracts numerical financial data.&quot;<br>        }<br>    }<br>)</pre><p>Above, we are dictating that the LLM must act as an assistant that extracts numerical financial data. Let’s look at its response:</p><pre>data[&#39;extract&#39;]</pre><pre>{&#39;financial_data&#39;: [<br>        {<br>            &#39;amount&#39;: 121200000,<br>            &#39;context&#39;: &#39;René Magritte became the 16th artist whose work broke the nine-figure &#39;<br>                      &#39;threshold at auction when his painting sold for $121.2 million.&#39;,<br>            &#39;article_link&#39;: &#39;https://www.nytimes.com/2024/11/19/arts/design/magritte-surrealism-christies-auction.html&#39;<br>        },<br>        {<br>            &#39;amount&#39;: 5000000,<br>            &#39;context&#39;: &#39;Benjamin Netanyahu offers $5 million for each hostage freed in Gaza.&#39;,<br>            &#39;article_link&#39;: &#39;https://www.nytimes.com/2024/11/19/world/middleeast/israel-5-million-dollars-hostage.html&#39;<br>        }<br>    ]}</pre><p>The output shows the LLM successfully extracted two financial data points from the articles.</p><p>The LLM not only identified the specific amounts but also provided relevant context and source article links for each figure.</p><h4>Schema-Based Data Extraction — Building Structured Models</h4><p>While natural language scraping is powerful for exploration and prototyping, production systems typically require more structured and deterministic approaches. LLM responses can vary between runs of the same prompt, making the output format inconsistent and difficult to reliably parse in automated workflows.</p><p>For this reason, Firecrawl allows you to pass a predefined schema to guide the LLM’s output when transforming the scraped content. To facilitate this feature, Firecrawl uses Pydantic models.</p><p>In the example below, we will extract only news article links, their titles with some additional details from the New York Times:</p><pre>from pydantic import BaseModel, Field<br><br>class IndividualArticle(BaseModel):<br>    title: str = Field(description=&quot;The title of the news article&quot;)<br>    subtitle: str = Field(description=&quot;The subtitle of the news article&quot;)<br>    url: str = Field(description=&quot;The URL of the news article&quot;)<br>    author: str = Field(description=&quot;The author of the news article&quot;)<br>    date: str = Field(description=&quot;The date the news article was published&quot;)<br>    read_duration: int = Field(description=&quot;The estimated time it takes to read the news article&quot;)<br>    topics: list[str] = Field(description=&quot;A list of topics the news article is about&quot;)<br>class NewsArticlesSchema(BaseModel):<br>    news_articles: list[IndividualArticle] = Field(<br>        description=&quot;A list of news articles extracted from the page&quot;<br>    )</pre><p>Above, we define a Pydantic schema that specifies the structure of the data we want to extract. The schema consists of two models:</p><p>IndividualArticle defines the structure for individual news articles with fields for:</p><ul><li>title</li><li>subtitle</li><li>url</li><li>author</li><li>date</li><li>read_duration</li><li>topics</li></ul><p>NewsArticlesSchema acts as a container model that holds a list of IndividualArticle objects, representing multiple articles extracted from the page. If we don’t use this container model, Firecrawl will only return the first news article it finds.</p><p>Each model field uses Pydantic’s Field class to provide descriptions that help guide the LLM in correctly identifying and extracting the requested data. This structured approach ensures consistent output formatting.</p><p>The next step is passing this schema to the extract parameter of scrape_url:</p><pre>url = &quot;https://nytimes.com&quot;<br><br>structured_data = app.scrape_url(<br>    url,<br>    params={<br>        &quot;formats&quot;: [&quot;extract&quot;, &quot;screenshot&quot;],<br>        &quot;extract&quot;: {<br>            &quot;schema&quot;: NewsArticlesSchema.model_json_schema(),<br>            &quot;prompt&quot;: &quot;Extract the following data from the NY Times homepage: news article title, url, author, date, read_duration for all news articles&quot;,<br>            &quot;systemPrompt&quot;: &quot;You are a helpful assistant that extracts news article data from NY Times.&quot;,<br>        },<br>    },<br>)</pre><p>While passing the schema, we call its model_json_schema() method to automatically convert it to valid JSON. Let’s look at the output:</p><pre>structured_data[&#39;extract&#39;]</pre><pre>{<br>    &#39;news_articles&#39;: [<br>        {<br>            &#39;title&#39;: &#39;How Google Spent 15 Years Creating a Culture of Concealment&#39;,<br>            &#39;subtitle&#39;: &#39;&#39;,<br>            &#39;url&#39;: &#39;https://www.nytimes.com/2024/11/20/technology/google-antitrust-employee-messages.html&#39;,<br>            &#39;author&#39;: &#39;David Streitfeld&#39;,<br>            &#39;date&#39;: &#39;2024-11-20&#39;,<br>            &#39;read_duration&#39;: 9,<br>            &#39;topics&#39;: []<br>        },<br>        # ... additional articles ...<br>        {<br>            &#39;title&#39;: &#39;The Reintroduction of Daniel Craig&#39;,<br>            &#39;subtitle&#39;: &#39;&#39;,<br>            &#39;url&#39;: &#39;https://www.nytimes.com/2024/11/20/movies/daniel-craig-queer.html&#39;,<br>            &#39;author&#39;: &#39;&#39;,<br>            &#39;date&#39;: &#39;2024-11-20&#39;,<br>            &#39;read_duration&#39;: 9,<br>            &#39;topics&#39;: []<br>        }<br>    ]<br>}</pre><p>This time, the response fields exactly match the fields we set during the schema definition:</p><pre>{<br>    &quot;news_articles&quot;: [<br>        {...}, # Article 1<br>        {...}, # Article 2,<br>        ... # Article n<br>    ]<br>}</pre><p>When creating the scraping schema, the following best practices can go a long way in ensuring reliable and accurate data extraction:</p><ol><li>Keep field names simple and descriptive</li><li>Use clear field descriptions that guide the LLM</li><li>Break complex data into smaller, focused fields</li><li>Include validation rules where possible</li><li>Consider making optional fields that may not always be present</li><li>Test the schema with a variety of content examples</li><li>Iterate and refine based on extraction results</li></ol><p>To follow these best practices, the following Pydantic tips can help:</p><ol><li>Use Field(default=None) to make fields optional</li><li>Add validation with Field(min_length=1, max_length=100)</li><li>Create custom validators with @validator decorator</li><li>Use conlist() for list fields with constraints</li><li>Add example values with Field(example=&quot;Sample text&quot;)</li><li>Create nested models for complex data structures</li><li>Use computed fields with @property decorator</li></ol><p>If you follow all these tips, your schema can become quite sophisticated like the below:</p><pre>from pydantic import BaseModel, Field<br>from typing import Optional, List<br>from datetime import datetime<br><br>class Author(BaseModel):<br>    # Required field - must be provided when creating an Author<br>    name: str = Field(<br>        ...,<br>        min_length=1,<br>        max_length=100,<br>        description=&quot;The full name of the article author&quot;,<br>    )<br>    # Optional field - can be None or omitted<br>    title: Optional[str] = Field(<br>        None, description=&quot;Author&#39;s title or role, if available&quot;<br>    )<br><br>class NewsArticle(BaseModel):<br>    # Required field - must be provided when creating a NewsArticle<br>    title: str = Field(<br>        ...,<br>        min_length=5,<br>        max_length=300,<br>        description=&quot;The main headline or title of the news article&quot;,<br>        example=&quot;Breaking News: Major Scientific Discovery&quot;,<br>    )<br>    # Required field - must be provided when creating a NewsArticle<br>    url: str = Field(<br>        ...,<br>        description=&quot;The full URL of the article&quot;,<br>        example=&quot;https://www.nytimes.com/2024/01/01/science/discovery.html&quot;,<br>    )<br>    # Optional field - can be None or omitted<br>    authors: Optional[List[Author]] = Field(<br>        default=None, description=&quot;List of article authors and their details&quot;<br>    )<br>    # Optional field - can be None or omitted<br>    publish_date: Optional[datetime] = Field(<br>        default=None, description=&quot;When the article was published&quot;<br>    )<br>    # Optional field with default empty list<br>    financial_amounts: List[float] = Field(<br>        default_factory=list,<br>        max_length=10,<br>        description=&quot;Any monetary amounts mentioned in the article in USD&quot;,<br>    )<br>    @property<br>    def is_recent(self) -&gt; bool:<br>        if not self.publish_date:<br>            return False<br>        return (datetime.now() - self.publish_date).days &lt; 7</pre><p>The schema above defines two key data models for news article data:</p><p>Author — Represents article author information with:</p><ul><li>name (required): The author’s full name</li><li>title (optional): The author’s role or title</li></ul><p>NewsArticle — Represents a news article with:</p><ul><li>title (required): The article headline (5-300 chars)</li><li>url (required): Full article URL</li><li>authors (optional): List of Author objects</li><li>publish_date (optional): Article publication datetime</li><li>financial_amounts (optional): List of monetary amounts in USD</li></ul><p>The NewsArticle model includes an is_recent property that checks if the article was published within the last 7 days.</p><p>As you can see, the web scraping process becomes much easier and more powerful if you combine it with structured data models that validate and organize the scraped information. This allows for consistent data formats, type checking, and easy access to properties like checking if an article is recent.</p><h3>Large-scale Scraping With Batch Operations</h3><p>Up to this point, we have been focusing on scraping pages one URL at a time. In reality, you will work with multiple, perhaps, thousands of URLs that need to be scraped in parallel. This is where batch operations become essential for efficient web scraping at scale. Batch operations allow you to process multiple URLs simultaneously, significantly reducing the overall time needed to collect data from multiple web pages.</p><h4>Batch Scraping with batch_scrape_urls</h4><p>The batch_scrape_urls method lets you scrape multiple URLs at once.</p><p>Let’s scrape all the news article links we obtained from our previous schema extraction example.</p><pre>articles = structured_data[&#39;extract&#39;][&#39;news_articles&#39;]<br>article_links = [article[&#39;url&#39;] for article in articles]<br><br>class ArticleSummary(BaseModel):<br>    title: str = Field(description=&quot;The title of the news article&quot;)<br>    summary: str = Field(description=&quot;A short summary of the news article&quot;)<br>batch_data = app.batch_scrape_urls(article_links, params={<br>    &quot;formats&quot;: [&quot;extract&quot;],<br>    &quot;extract&quot;: {<br>        &quot;schema&quot;: ArticleSummary.model_json_schema(),<br>        &quot;prompt&quot;: &quot;Extract the title of the news article and generate its brief summary&quot;,<br>    }<br>})</pre><p>Here is what is happening in the code block above:</p><ul><li>We extract the list of news articles from our previous structured data result</li><li>We create a list of article URLs by mapping over the articles and getting their ‘URL’ field</li><li>We define an ArticleSummary model with title and summary fields to structure our output</li><li>We use batch_scrape_urls() to process all article URLs in parallel, configuring it to:</li><li>Extract data in a structured format</li><li>Use our ArticleSummary schema</li><li>Generate titles and summaries based on the article content</li></ul><p>The response from batch_scrape_urls() is a bit different:</p><pre>batch_data.keys()</pre><pre>dict_keys([&#39;success&#39;, &#39;status&#39;, &#39;completed&#39;, &#39;total&#39;, &#39;creditsUsed&#39;, &#39;expiresAt&#39;, &#39;data&#39;])</pre><p>It contains the following fields:</p><ul><li>success: Boolean indicating if the batch request succeeded</li><li>status: Current status of the batch job</li><li>completed: Number of URLs processed so far</li><li>total: Total number of URLs in the batch</li><li>creditsUsed: Number of API credits consumed</li><li>expiresAt: When the results will expire</li><li>data: The extracted data for each URL</li></ul><p>Let’s focus on the data key where the actual content is stored:</p><pre>len(batch_data[&#39;data&#39;])</pre><pre>19</pre><p>The batch processing was completed successfully with 19 articles. Let’s examine the structure of the first article:</p><pre>batch_data[&#39;data&#39;][0].keys()</pre><pre>dict_keys([&#39;extract&#39;, &#39;metadata&#39;])</pre><pre>print(batch_data[&#39;data&#39;][0][&#39;extract&#39;])</pre><pre>{&#39;title&#39;: &#39;Ukrainian Forces Face Increasing Challenges Amidst Harsh Winter Conditions&#39;, <br> &#39;summary&#39;: &#39;As the war in Ukraine enters its fourth winter, conditions are worsening for Ukrainian soldiers who find themselves trapped on the battlefield, surrounded by Russian forces. Military commanders express concerns over dwindling supplies and increasingly tough situations. The U.S. has recently allowed Ukraine to use American weapons for deeper strikes into Russia, marking a significant development in the ongoing conflict.&#39;}</pre><p>The scraping was performed according to our specifications, extracting the metadata, and the title and generating a summary.</p><h4>Asynchronous batch scraping with async_batch_scrape_urls</h4><p>Scraping the 19 NY Times articles in a batch took about 10 seconds on my machine. While that’s not much, in practice, we cannot wait around as Firecrawl batch-scrapes thousands of URLs. For these larger workloads, Firecrawl provides an asynchronous batch scraping API that lets you submit jobs and check their status later, rather than blocking them until completion. This is especially useful when integrating web scraping into automated workflows or processing large URL lists.</p><p>This feature is available through the async_batch_scrape_urls method and it works a bit differently:</p><pre>batch_scrape_job = app.async_batch_scrape_urls(<br>    article_links,<br>    params={<br>        &quot;formats&quot;: [&quot;extract&quot;],<br>        &quot;extract&quot;: {<br>            &quot;schema&quot;: ArticleSummary.model_json_schema(),<br>            &quot;prompt&quot;: &quot;Extract the title of the news article and generate its brief summary&quot;,<br>        },<br>    },<br>)</pre><p>When using async_batch_scrape_urls instead of the synchronous version, the response comes back immediately rather than waiting for all URLs to be scraped. This allows the program to continue executing while the scraping happens in the background.</p><pre>batch_scrape_job</pre><pre>{&#39;success&#39;: True,<br>     &#39;id&#39;: &#39;77a94b62-c676-4db2-b61b-4681e99f4704&#39;,<br>     &#39;url&#39;: &#39;https://api.firecrawl.dev/v1/batch/scrape/77a94b62-c676-4db2-b61b-4681e99f4704&#39;}</pre><p>The response contains an ID belonging to the background task that was initiated to process the URLs under the hood.</p><p>You can use this ID later to check the job’s status with check_batch_scrape_status method:</p><pre>batch_scrape_job_status = app.check_batch_scrape_status(batch_scrape_job[&#39;id&#39;])<br><br>batch_scrape_job_status.keys()</pre><pre>dict_keys([&#39;success&#39;, &#39;status&#39;, &#39;total&#39;, &#39;completed&#39;, &#39;creditsUsed&#39;, &#39;expiresAt&#39;, &#39;data&#39;, &#39;error&#39;, &#39;next&#39;])</pre><p>If the job finished scraping all URLs, its status will be set to completed:</p><pre>batch_scrape_job_status[&#39;status&#39;]</pre><pre>&#39;completed&#39;</pre><p>Let’s look at how many pages were scraped:</p><pre>batch_scrape_job_status[&#39;total&#39;]</pre><pre>19</pre><p>The response always includes the data field, whether the job is complete or not, with the content scraped up to that point. It has error and next fields to indicate if any errors occurred during scraping and whether there are more results to fetch.</p><h3>How to Scrape Dynamic JavaScript Websites</h3><p>Out in the wild, many websites you encounter will be dynamic, meaning their content is generated on the fly using JavaScript rather than being pre-rendered on the server. These sites often require user interaction like clicking buttons or typing into forms before displaying their full content. Traditional web scrapers that only look at the initial HTML fail to capture this dynamic content, which is why browser automation capabilities are essential for comprehensive web scraping.</p><p>Firecrawl supports dynamic scraping by default. In the parameters of scrape_url or batch_scrape_url, you can define the necessary actions to reach the target state of the page you are scraping. As an example, we will build a scraper that will extract the following information from <a href="https://weather.com:">https://weather.com:</a></p><ul><li>Current Temperature</li><li>Temperature High</li><li>Temperature Low</li><li>Humidity</li><li>Pressure</li><li>Visibility</li><li>Wind Speed</li><li>Dew Point</li><li>UV Index</li><li>Moon Phase</li></ul><p>These details are displayed for every city you search through the website:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AZLsLPA5hvUb7aTS.png" /></figure><p>Unlike websites such as Amazon where you can simply modify the URL’s search parameter (e.g. ?search=your-query), weather.com presents a unique challenge. The site generates dynamic and unique IDs for each city, making traditional URL manipulation techniques ineffective. To scrape weather data for any given city, you must simulate the actual user journey: visiting the homepage, interacting with the search bar, entering the city name, and selecting the appropriate result from the dropdown list. This multi-step interaction process is necessary because of how weather.com structures its dynamic content delivery (at this point, I urge to visit the website and visit a few city pages).</p><p>Fortunately, Firecrawl natively supports such interactions through the actions parameter. It accepts a list of dictionaries, where each dictionary represents one of the following interactions:</p><ul><li>Waiting for the page to load</li><li>Clicking on an element</li><li>Writing text in input fields</li><li>Scrolling up/down</li><li>Take a screenshot of the current state</li><li>Scrape the current state of the webpage</li></ul><p>Let’s define the actions we need for weather.com:</p><pre>actions = [<br>    {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 3000},<br>    {&quot;type&quot;: &quot;click&quot;, &quot;selector&quot;: &#39;input[id=&quot;LocationSearch_input&quot;]&#39;},<br>    {&quot;type&quot;: &quot;write&quot;, &quot;text&quot;: &quot;London&quot;},<br>    {&quot;type&quot;: &quot;screenshot&quot;},<br>    {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 1000},<br>    {&quot;type&quot;: &quot;click&quot;, &quot;selector&quot;: &quot;button[data-testid=&#39;ctaButton&#39;]&quot;},<br>    {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 3000},<br>]</pre><p>Let’s examine how we choose the selectors, as this is the most technical aspect of the actions. Using browser developer tools, we inspect the webpage elements to find the appropriate selectors. For the search input field, we locate an element with the ID “LocationSearch_input”. After entering a city name, we include a 3-second wait to allow the dropdown search results to appear. At this stage, we capture a screenshot for debugging to verify the text input was successful.</p><p>The final step involves clicking the first matching result, which is identified by a button element with the data-testid attribute ctaButton. Note that if you’re implementing this in the future, these specific attribute names may have changed - you’ll need to use browser developer tools to find the current correct selectors.</p><p>Now, let’s define a Pydantic schema to guide the LLM:</p><pre>class WeatherData(BaseModel):<br>    location: str = Field(description=&quot;The name of the city&quot;)<br>    temperature: str = Field(description=&quot;The current temperature in degrees Fahrenheit&quot;)<br>    temperature_high: str = Field(description=&quot;The high temperature for the day in degrees Fahrenheit&quot;)<br>    temperature_low: str = Field(description=&quot;The low temperature for the day in degrees Fahrenheit&quot;)<br>    humidity: str = Field(description=&quot;The current humidity as a percentage&quot;)<br>    pressure: str = Field(description=&quot;The current air pressure in inches of mercury&quot;)<br>    visibility: str = Field(description=&quot;The current visibility in miles&quot;)<br>    wind_speed: str = Field(description=&quot;The current wind speed in miles per hour&quot;)<br>    dew_point: str = Field(description=&quot;The current dew point in degrees Fahrenheit&quot;)<br>    uv_index: str = Field(description=&quot;The current UV index&quot;)<br>    moon_phase: str = Field(description=&quot;The current moon phase&quot;)</pre><p>Finally, let’s pass these objects to scrape_url:</p><pre>url = &quot;https://weather.com&quot;<br><br>data = app.scrape_url(<br>    url,<br>    params={<br>        &quot;formats&quot;: [&quot;screenshot&quot;, &quot;markdown&quot;, &quot;extract&quot;],<br>        &quot;actions&quot;: actions,<br>        &quot;extract&quot;: {<br>            &quot;schema&quot;: WeatherData.model_json_schema(),<br>            &quot;prompt&quot;: &quot;Extract the following weather data from the weather.com page: temperature, temperature high, temperature low, humidity, pressure, visibility, wind speed, dew point, UV index, and moon phase&quot;,<br>        },<br>    },<br>)</pre><p>The scraping only happens once all actions are performed. Let’s see if it was successful by looking at the extract key:</p><pre>data[&#39;extract&#39;]</pre><pre>{&#39;location&#39;: &#39;London, England, United Kingdom&#39;,<br>     &#39;temperature&#39;: &#39;33°&#39;,<br>     &#39;temperature_high&#39;: &#39;39°&#39;,<br>     &#39;temperature_low&#39;: &#39;33°&#39;,<br>     &#39;humidity&#39;: &#39;79%&#39;,<br>     &#39;pressure&#39;: &#39;29.52in&#39;,<br>     &#39;visibility&#39;: &#39;10 mi&#39;,<br>     &#39;wind_speed&#39;: &#39;5 mph&#39;,<br>     &#39;dew_point&#39;: &#39;28°&#39;,<br>     &#39;uv_index&#39;: &#39;0 of 11&#39;,<br>     &#39;moon_phase&#39;: &#39;Waning Gibbous&#39;}</pre><p>All details are accounted for! But, for illustration, we need to take a closer look at the response structure when using JS-based actions:</p><pre>data.keys()</pre><pre>dict_keys([&#39;markdown&#39;, &#39;screenshot&#39;, &#39;actions&#39;, &#39;metadata&#39;, &#39;extract&#39;])</pre><p>The response has a new action key:</p><pre>data[&#39;actions&#39;]</pre><pre>{&#39;screenshots&#39;: [&#39;https://service.firecrawl.dev/storage/v1/object/public/media/screenshot-16bf71d8-dcb5-47eb-9af4-5fa84195b91d.png&#39;],<br>     &#39;scrapes&#39;: []}</pre><p>The actions array contained a single screenshot-generating action, which is reflected in the output above.</p><p>Let’s look at the screenshot:</p><pre>from IPython.display import Image<br><br>Image(data[&#39;actions&#39;][&#39;screenshots&#39;][0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xn62bGc-vfySzDmH.png" /></figure><p>The image shows the stage where the scraper just typed the search query.</p><p>Now, we have to convert this whole process into a function that works for any given city:</p><pre>from pydantic import BaseModel, Field<br>from typing import Optional, Dict, Any<br><br><br>class WeatherData(BaseModel):<br>    location: str = Field(description=&quot;The name of the city&quot;)<br>    temperature: str = Field(<br>        description=&quot;The current temperature in degrees Fahrenheit&quot;<br>    )<br>    temperature_high: str = Field(<br>        description=&quot;The high temperature for the day in degrees Fahrenheit&quot;<br>    )<br>    temperature_low: str = Field(<br>        description=&quot;The low temperature for the day in degrees Fahrenheit&quot;<br>    )<br>    humidity: str = Field(description=&quot;The current humidity as a percentage&quot;)<br>    pressure: str = Field(description=&quot;The current air pressure in inches of mercury&quot;)<br>    visibility: str = Field(description=&quot;The current visibility in miles&quot;)<br>    wind_speed: str = Field(description=&quot;The current wind speed in miles per hour&quot;)<br>    dew_point: str = Field(description=&quot;The current dew point in degrees Fahrenheit&quot;)<br>    uv_index: str = Field(description=&quot;The current UV index&quot;)<br>    moon_phase: str = Field(description=&quot;The current moon phase&quot;)<br><br>def scrape_weather_data(app: FirecrawlApp, city: str) -&gt; Optional[WeatherData]:<br>    try:<br>        # Define the actions to search for the city<br>        actions = [<br>            {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 3000},<br>            {&quot;type&quot;: &quot;click&quot;, &quot;selector&quot;: &#39;input[id=&quot;LocationSearch_input&quot;]&#39;},<br>            {&quot;type&quot;: &quot;write&quot;, &quot;text&quot;: city},<br>            {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 1000},<br>            {&quot;type&quot;: &quot;click&quot;, &quot;selector&quot;: &quot;button[data-testid=&#39;ctaButton&#39;]&quot;},<br>            {&quot;type&quot;: &quot;wait&quot;, &quot;milliseconds&quot;: 3000},<br>        ]<br>        # Perform the scraping<br>        data = app.scrape_url(<br>            &quot;https://weather.com&quot;,<br>            params={<br>                &quot;formats&quot;: [&quot;extract&quot;],<br>                &quot;actions&quot;: actions,<br>                &quot;extract&quot;: {<br>                    &quot;schema&quot;: WeatherData.model_json_schema(),<br>                    &quot;prompt&quot;: &quot;Extract the following weather data from the weather.com page: temperature, temperature high, temperature low, humidity, pressure, visibility, wind speed, dew point, UV index, and moon phase&quot;,<br>                },<br>            },<br>        )<br>        # Return the extracted weather data<br>        return WeatherData(**data[&quot;extract&quot;])<br>    except Exception as e:<br>        print(f&quot;Error scraping weather data for {city}: {str(e)}&quot;)<br>        return None</pre><p>The code is the same but it is wrapped inside a function. Let’s test it on various cities:</p><pre>cities = [&quot;Tashkent&quot;, &quot;New York&quot;, &quot;Tokyo&quot;, &quot;Paris&quot;, &quot;Istanbul&quot;]<br>data_full = []<br><br>for city in cities:<br>    weather_data = scrape_weather_data(app, city)<br>    data_full.append(weather_data)</pre><p>We can convert the data for all cities into a DataFrame now:</p><pre>import pandas as pd<br><br># Convert list of WeatherData objects into dictionaries<br>data_dicts = [city.model_dump() for city in data_full]<br># Convert list of dictionaries into DataFrame<br>df = pd.DataFrame(data_dicts)<br>print(df.head())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*9XtFNNqtjjbsW5W9C0pCfQ.png" /></figure><p>We have successfully scraped weather data from multiple cities using Firecrawl and organized it into a structured DataFrame. This demonstrates how we can efficiently collect and analyze data generated by dynamic websites for further analysis and monitoring.</p><h3>Conclusion</h3><p>In this comprehensive guide, we’ve explored Firecrawl’s /scrape endpoint and its powerful capabilities for modern web scraping. We covered:</p><ul><li>Basic scraping setup and configuration options</li><li>Multiple output formats including HTML, markdown, and screenshots</li><li>Structured data extraction using both natural language prompts and Pydantic schemas</li><li>Batch operations for processing multiple URLs efficiently</li><li>Advanced techniques for scraping JavaScript-heavy dynamic websites</li></ul><p>The combination of LLM-powered extraction, structured schemas, and browser automation capabilities makes Firecrawl a versatile tool for gathering high-quality web data at scale, whether you’re building training datasets, monitoring websites, or conducting research.</p><p>To discover more about what Firecrawl has to offer, refer to <a href="https://www.firecrawl.dev/blog/mastering-the-crawl-endpoint-in-firecrawl">this guide on the </a><a href="https://www.firecrawl.dev/blog/mastering-the-crawl-endpoint-in-firecrawl">/crawl endpoint</a>, which scrapes websites in their entirety with a single command while using the /scrape endpoint under the hood.</p><p>For more hands-on uses of Firecrawl, these posts may interest you as well:</p><p><a href="https://medium.datadriveninvestor.com/firecrawl-how-to-scrape-entire-websites-with-a-single-command-in-python-5a8940183c91">Firecrawl: How to Scrape Entire Websites With a Single Command in Python</a></p><ul><li><a href="https://www.firecrawl.dev/blog/using-prompt-caching-with-anthropic">Using Prompt Caching With Anthropic</a></li><li><a href="https://www.firecrawl.dev/blog/scrape-job-boards-firecrawl-openai">Scraping Job Boards With Firecrawl and OpenAI</a></li><li><a href="https://www.firecrawl.dev/blog/scrape-analyze-airbnb-data-with-e2b">Scraping and Analyzing Airbnb Listings in Python Tutorial</a></li></ul><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553e16fa8b5a" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/firecrawl-scrape-any-website-using-ai-and-bypass-blockers-in-python-553e16fa8b5a">Firecrawl: Scrape Any Website Using AI and Bypass Blockers in Python</a> was originally published in <a href="https://medium.datadriveninvestor.com">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firecrawl: How to Scrape Entire Websites With a Single Command in Python]]></title>
            <link>https://medium.datadriveninvestor.com/firecrawl-how-to-scrape-entire-websites-with-a-single-command-in-python-5a8940183c91?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a8940183c91</guid>
            <category><![CDATA[web-crawling]]></category>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[data-extraction]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 05:26:55 GMT</pubDate>
            <atom:updated>2024-12-05T09:53:11.517Z</atom:updated>
            <content:encoded><![CDATA[<h4>And turn them into LLM-ready data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YdEComu_UrmI6kXzj5_6zA.jpeg" /><figcaption>Image by me.</figcaption></figure><h3>Introduction</h3><p>Web scraping and data extraction have become essential tools as businesses race to convert unprecedented amounts of online data into LLM-friendly formats. Firecrawl’s powerful web scraping API streamlines this process with enterprise-grade automation and scalability features.</p><p>This comprehensive guide focuses on Firecrawl’s most powerful feature — the /crawl endpoint, which enables automated website scraping at scale. You’ll learn how to:</p><ul><li>Recursively traverse website sub-pages</li><li>Handle dynamic JavaScript-based content</li><li>Bypass common web scraping blockers</li><li>Extract clean, structured data for AI/ML applications</li></ul><p>Want to follow along with a Python notebook version of this post? <a href="https://github.com/mendableai/firecrawl/blob/main/examples/blog-articles/mastering-the-crawl-endpoint/mastering-the-crawl-endpoint.ipynb">Check it out here</a>!</p><h3>Web Scraping vs Web Crawling: Understanding the Key Differences</h3><p><em>Web scraping</em> refers to extracting specific data from individual web pages like a Wikipedia article or a technical tutorial. It is primarily used when you need specific information from pages with <em>known URLs</em>.</p><p><em>Web crawling</em>, on the other hand, involves systematically browsing and discovering web pages by following links. It focuses on website navigation and URL discovery.</p><p>For example, to build a chatbot that answers questions about Stripe’s documentation, you would need:</p><ol><li>Web crawling to discover and traverse all pages in Stripe’s documentation site</li><li>Web scraping to extract the actual content from each discovered page</li></ol><h4><strong>How Firecrawl Combines Both</strong></h4><p>Firecrawl’s /crawl endpoint combines both capabilities:</p><ol><li>URL analysis: Identifies links through sitemap or page traversal</li><li>Recursive traversal: Follows links to discover sub-pages</li><li>Content scraping: Extracts clean content from each page</li><li>Results compilation: Converts everything to structured data</li></ol><p>When you pass the URL https://docs.stripe.com/api to the endpoint, it automatically discovers and crawls all documentation sub-pages. The endpoint returns the content in your preferred format - whether that’s markdown, HTML, screenshots, links, or metadata.</p><h3>Step-by-Step Guide to Web Crawling with Firecrawl’s API</h3><p>Firecrawl is a web scraping engine exposed as a REST API. You can use it from the command line using cURL or using one of its language SDKs for Python, Node, Go, or Rust. For this tutorial, we’ll focus on its Python SDK.</p><p>To get started:</p><ol><li>Sign up at <a href="https://firecrawl.dev/">firecrawl.dev</a> and copy your API key</li><li>Save the key as an environment variable:</li></ol><pre>export FIRECRAWL_API_KEY=&#39;fc-YOUR-KEY-HERE&#39;</pre><p>Or use a dot-env file:</p><pre>touch .env<br>echo &quot;FIRECRAWL_API_KEY=&#39;fc-YOUR-KEY-HERE&#39;&quot; &gt;&gt; .env</pre><p>Then use the Python SDK:</p><pre>from firecrawl import FirecrawlApp<br>from dotenv import load_dotenv<br><br>load_dotenv()<br>app = FirecrawlApp()</pre><p>Once your API key is loaded, the FirecrawlApp class uses it to establish a connection with the Firecrawl API engine.</p><p>First, we will crawl the <a href="https://books.toscrape.com/">https://books.toscrape.com/</a> website, which is built for web-scraping practice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-OGiLMRXGNDAyBQm.png" /></figure><p>Instead of writing dozens of lines of code with libraries like beautifulsoup4 or lxml to parse HTML elements, handle pagination and data retrieval, Firecrawl’s crawl_url endpoint lets you accomplish this in a single line:</p><pre>base_url = &quot;https://books.toscrape.com/&quot;<br>crawl_result = app.crawl_url(url=base_url)</pre><p>The result is a dictionary with the following keys:</p><pre>crawl_result.keys()</pre><pre>dict_keys([&#39;success&#39;, &#39;status&#39;, &#39;completed&#39;, &#39;total&#39;, &#39;creditsUsed&#39;, &#39;expiresAt&#39;, &#39;data&#39;])</pre><p>First, we are interested in the status of the crawl job:</p><pre>crawl_result[&#39;status&#39;]</pre><pre>&#39;completed&#39;</pre><p>If it is completed, let’s see how many pages were scraped:</p><pre>crawl_result[&#39;total&#39;]</pre><pre>1195</pre><p>Almost 1200 pages (it took about 70 seconds on my machine; the speed vary based on your connection speed). Let’s look at one of the elements of the data list:</p><pre>sample_page = crawl_result[&#39;data&#39;][10]<br>markdown_content = sample_page[&#39;markdown&#39;]<br><br>print(markdown_content[:500])</pre><pre>- [Home](../../../../index.html)<br>- [Books](../../books_1/index.html)<br>- Womens Fiction<br><br># Womens Fiction<br>**17** results.<br>**Warning!** This is a demo website for web scraping purposes. Prices and ratings here were randomly assigned and have no real meaning.<br>01. [![I Had a Nice Time And Other Lies...: How to find love &amp; sh*t like that](../../../../media/cache/5f/72/5f72c8a0d5a7292e2929a354ec8a022f.jpg)](../../../i-had-a-nice-time-and-other-lies-how-to-find-love-sht-like-that_814/index.html)</pre><p>The page corresponds to the Women’s Fiction page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dgJrGWbA-xcZzIkR.png" /></figure><p>Firecrawl also includes page metadata in the element’s dictionary as well:</p><pre>sample_page[&#39;metadata&#39;]</pre><pre>{<br>    &#39;url&#39;: &#39;https://books.toscrape.com/catalogue/category/books/womens-fiction_9/index.html&#39;,<br>    &#39;title&#39;: &#39;Womens Fiction | Books to Scrape - Sandbox&#39;,<br>    &#39;robots&#39;: &#39;NOARCHIVE,NOCACHE&#39;, <br>    &#39;created&#39;: &#39;24th Jun 2016 09:29&#39;,<br>    &#39;language&#39;: &#39;en-us&#39;,<br>    &#39;viewport&#39;: &#39;width=device-width&#39;,<br>    &#39;sourceURL&#39;: &#39;https://books.toscrape.com/catalogue/category/books/womens-fiction_9/index.html&#39;,<br>    &#39;statusCode&#39;: 200,<br>    &#39;description&#39;: &#39;&#39;,<br>    &#39;ogLocaleAlternate&#39;: []<br>}</pre><p>One thing we didn’t mention is how Firecrawl handles pagination. If you scroll to the bottom of Books-to-Scrape, you will see that it has a “next” button.</p><p>Before moving on to sub-pages like books.toscrape.com/category, Firecrawl first scrapes all sub-pages from the homepage. Later, if a sub-page includes links to already scraped pages, they are ignored.</p><h3>Advanced Web Scraping Configuration and Best Practices</h3><p>Firecrawl offers several types of parameters to configure how the endpoint crawls over websites. We will outline them here with their use cases.</p><h4><strong>Scrape Options</strong></h4><p>On real-world projects, you will tweak this parameter the most frequently. It allows you to control how a web page’s contents are saved. Firecrawl allows the following formats:</p><ul><li>Markdown — the default</li><li>HTML</li><li>Raw HTML (simple copy/paste of the entire webpage)</li><li>Links</li><li>Screenshot</li></ul><p>Here is an example request to scrape the Stripe API in four formats:</p><pre># Crawl the first 5 pages of the stripe API documentation<br>stripe_crawl_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/api&quot;,<br>    params={<br>        &quot;limit&quot;: 5,  # Only scrape the first 5 pages including the base-url<br>        &quot;scrapeOptions&quot;: {<br>            &quot;formats&quot;: [&quot;markdown&quot;, &quot;html&quot;, &quot;links&quot;, &quot;screenshot&quot;]<br>        }<br>    }<br>)</pre><p>When you specify multiple formats, each webpage’s data contains separate keys for each format’s content:</p><pre>stripe_crawl_result[&#39;data&#39;][0].keys()</pre><pre>dict_keys([&#39;html&#39;, &#39;links&#39;, &#39;markdown&#39;, &#39;metadata&#39;, &#39;screenshot&#39;])</pre><p>The value of the screenshot key is a temporary link to a PNG file stored on Firecrawl’s servers and expires within 24 hours. Here is what it looks like for Stripe’s API documentation homepage:</p><pre>from IPython.display import Image<br><br>Image(stripe_crawl_result[&#39;data&#39;][0][&#39;screenshot&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XDCxsm1b2pVwkd-N.png" /></figure><p>Note that specifying more formats to transform the page’s contents can significantly slow down the process.</p><p>Another time-consuming operation can be scraping the entire page contents instead of just the elements you want. For such scenarios, Firecrawl allows you to control which elements of a webpage are scraped using the onlyMainContent, includeTags, and excludeTags parameters.</p><p>Enabling onlyMainContent parameter (disabled by default) excludes navigation, headers, and footers:</p><pre>stripe_crawl_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/api&quot;,<br>    params={<br>        &quot;limit&quot;: 5,<br>        &quot;scrapeOptions&quot;: {<br>            &quot;formats&quot;: [&quot;markdown&quot;, &quot;html&quot;], <br>            &quot;onlyMainContent&quot;: True,<br>        },<br>    },<br>)</pre><p>includeTags and excludeTags accepts a list of whitelisted/blacklisted HTML tags, classes, and IDs:</p><pre># Crawl the first 5 pages of the stripe API documentation<br>stripe_crawl_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/api&quot;,<br>    params={<br>        &quot;limit&quot;: 5,<br>        &quot;scrapeOptions&quot;: {<br>            &quot;formats&quot;: [&quot;markdown&quot;, &quot;html&quot;],<br>            &quot;includeTags&quot;: [&quot;code&quot;, &quot;#page-header&quot;],<br>            &quot;excludeTags&quot;: [&quot;h1&quot;, &quot;h2&quot;, &quot;.main-content&quot;],<br>        },<br>    },<br>)</pre><p>Crawling large websites can take a long time and when appropriate, these small tweaks can have a big impact on the runtime.</p><h4><strong>URL Control</strong></h4><p>Apart from scraping configurations, you have four options to specify URL patterns to include or exclude during crawling:</p><ul><li>includePaths - targeting specific sections</li><li>excludePaths - avoiding unwanted content</li><li>allowBackwardLinks - handling cross-references</li><li>allowExternalLinks - managing external content</li></ul><p>Here is a sample request that uses these parameters:</p><pre># Example of URL control parameters<br>url_control_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/&quot;,<br>    params={<br>        # Only crawl pages under the /payments path<br>        &quot;includePaths&quot;: [&quot;/payments/*&quot;],<br>        # Skip the terminal and financial-connections sections<br>        &quot;excludePaths&quot;: [&quot;/terminal/*&quot;, &quot;/financial-connections/*&quot;],<br>        # Allow crawling links that point to already visited pages<br>        &quot;allowBackwardLinks&quot;: False,<br>        # Don&#39;t follow links to external domains<br>        &quot;allowExternalLinks&quot;: False,<br>        &quot;scrapeOptions&quot;: {<br>            &quot;formats&quot;: [&quot;html&quot;]<br>        }<br>    }<br>)<br><br># Print the total number of pages crawled<br>print(f&quot;Total pages crawled: {url_control_result[&#39;total&#39;]}&quot;)</pre><pre>Total pages crawled: 134</pre><p>In this example, we’re crawling the Stripe documentation website with specific URL control parameters:</p><ul><li>The crawler starts at <a href="https://docs.stripe.com/">https://docs.stripe.com/</a> and only crawls pages under the &quot;/payments/*&quot; path</li><li>It explicitly excludes the &quot;/terminal/*&quot; and &quot;/financial-connections/*&quot; sections</li><li>By setting allowBackwardLinks to false, it won’t revisit already crawled pages</li><li>External links are ignored (allowExternalLinks: false)</li><li>The scraping is configured to only capture HTML content</li></ul><p>This targeted approach helps focus the crawl on relevant content while avoiding unnecessary pages, making the crawl more efficient and focused on the specific documentation sections we need.</p><p>Another critical parameter is maxDepth, which lets you control how many levels deep the crawler will traverse from the starting URL. For example, a maxDepth of 2 means it will crawl the initial page and pages linked from it, but won’t go further.</p><p>Here is another sample request on the Stripe API docs:</p><pre># Example of URL control parameters<br>url_control_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/&quot;,<br>    params={<br>        &quot;limit&quot;: 100,<br>        &quot;maxDepth&quot;: 2,<br>        &quot;allowBackwardLinks&quot;: False,<br>        &quot;allowExternalLinks&quot;: False,<br>        &quot;scrapeOptions&quot;: {&quot;formats&quot;: [&quot;html&quot;]},<br>    },<br>)<br><br># Print the total number of pages crawled<br>print(f&quot;Total pages crawled: {url_control_result[&#39;total&#39;]}&quot;)</pre><pre>Total pages crawled: 99</pre><p>Note: When a page has pagination (e.g. pages 2, 3, 4), these paginated pages are not counted as additional depth levels when using maxDepth.</p><h4><strong>Performance &amp; Limits</strong></h4><p>The limit parameter, which we’ve used in previous examples, is essential for controlling the scope of web crawling. It sets the maximum number of pages that will be scraped, which is particularly important when crawling large websites or when external links are enabled. Without this limit, the crawler could potentially traverse an endless chain of connected pages, consuming unnecessary resources and time.</p><p>While the limit parameter helps control the breadth of crawling, you may also need to ensure the quality and completeness of each page crawled. To make sure all desired content is scraped, you can enable a waiting period to let pages fully load. For example, some websites use JavaScript to handle dynamic content, and have iFrames for embedding content or heavy media elements like videos or GIFs:</p><pre>stripe_crawl_result = app.crawl_url(<br>    url=&quot;https://docs.stripe.com/api&quot;,<br>    params={<br>        &quot;limit&quot;: 5,<br>        &quot;scrapeOptions&quot;: {<br>            &quot;formats&quot;: [&quot;markdown&quot;, &quot;html&quot;],<br>            &quot;waitFor&quot;: 1000,  # wait for a second for pages to load<br>            &quot;timeout&quot;: 10000,  # timeout after 10 seconds<br>        },<br>    },<br>)</pre><p>The above code also sets the timeout parameter to 10000 milliseconds (10 seconds), which ensures that if a page takes too long to load, the crawler will move on rather than get stuck.</p><p>Note: waitFor duration applies to all pages the crawler encounters.</p><p>All the while, it is important to keep the limits of your plan in mind:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P0pDewB18QxEavVM4nS8Hg.png" /></figure><h3><strong>Asynchronous Web Crawling with Firecrawl: Efficient Large-Scale Data Collection</strong></h3><p>Even after following the tips and best practices from the previous section, the crawling process can be significantly long for large websites with thousands of pages. To handle this efficiently, Firecrawl provides asynchronous crawling capabilities that allow you to start a crawl and monitor its progress without blocking your application. This is particularly useful when building web applications or services that need to remain responsive while crawling is in progress.</p><h4>Asynchronous programming in a nutshell</h4><p>First, let’s understand asynchronous programming with a real-world analogy:</p><p>Asynchronous programming is like a restaurant server taking multiple orders at once. Instead of waiting at one table until the customers finish their meal before moving to the next table, they can take orders from multiple tables, submit them to the kitchen, and handle other tasks while the food is being prepared.</p><p>In programming terms, this means your code can initiate multiple operations (like web requests or database queries) and continue executing other tasks while waiting for responses, rather than processing everything sequentially.</p><p>This approach is particularly valuable in web crawling, where most of the time is spent waiting for network responses — instead of freezing the entire application while waiting for each page to load, async programming allows you to process multiple pages concurrently, dramatically improving efficiency.</p><h4>Using async_crawl_url method</h4><p>Firecrawl offers an intuitive asynchronous crawling method via async_crawl_url:</p><pre>app = FirecrawlApp()<br><br>crawl_status = app.async_crawl_url(&quot;https://docs.stripe.com&quot;)<br>print(crawl_status)</pre><pre>{&#39;success&#39;: True, &#39;id&#39;: &#39;c4a6a749-3445-454e-bf5a-f3e1e6befad7&#39;, &#39;url&#39;: &#39;https://api.firecrawl.dev/v1/crawl/c4a6a749-3445-454e-bf5a-f3e1e6befad7&#39;}</pre><p>It accepts the same parameters and scrape options as crawl_url but returns a crawl status dictionary.</p><p>We are mostly interested in the crawl job id and can use it to check the status of the process using check_crawl_status:</p><pre>checkpoint = app.check_crawl_status(crawl_status[&#39;id&#39;])<br><br>print(len(checkpoint[&#39;data&#39;]))</pre><pre>29</pre><p>check_crawl_status returns the same output as crawl_url but only includes the pages scraped so far. You can run it multiple times and see the number of scraped pages increasing.</p><p>If you want to cancel the job, you can use cancel_crawl passing the job id:</p><pre>final_result = app.cancel_crawl(crawl_status[&#39;id&#39;])<br><br>print(final_result)</pre><pre>{&#39;status&#39;: &#39;cancelled&#39;}</pre><h4>Benefits of asynchronous crawling</h4><p>There are many advantages to using the async_crawl_url over crawl_url:</p><ul><li>You can create multiple crawl jobs without waiting for each to complete.</li><li>You can monitor progress and manage resources more effectively.</li><li>Perfect for batch processing or parallel crawling tasks.</li><li>Applications can remain responsive while crawling happens in the background</li><li>Users can monitor progress instead of waiting for completion</li><li>Allows for implementing progress bars or status updates</li><li>Easier to integrate with message queues or job schedulers</li><li>Can be part of larger automated workflows</li><li>Better suited for microservices architectures</li></ul><p>In practice, you almost always use asynchronous crawling for large websites.</p><h3>How to Save and Store Web Crawling Results</h3><p>When crawling large websites, it’s important to save the results persistently. Firecrawl provides the crawled data in a structured format that can be easily saved to various storage systems. Let’s explore some common approaches.</p><h4><strong>Local file storage</strong></h4><p>The simplest approach is saving to local files. Here’s how to save crawled content in different formats:</p><pre>import json<br>from pathlib import Path<br><br>def save_crawl_results(crawl_result, output_dir=&quot;firecrawl_output&quot;):<br>    # Create output directory if it doesn&#39;t exist<br>    Path(output_dir).mkdir(parents=True, exist_ok=True)<br>    # Save full results as JSON<br>    with open(f&quot;{output_dir}/full_results.json&quot;, &quot;w&quot;) as f:<br>        json.dump(crawl_result, f, indent=2)<br>    # Save just the markdown content in separate files<br>    for idx, page in enumerate(crawl_result[&quot;data&quot;]):<br>        # Create safe filename from URL<br>        filename = (<br>            page[&quot;metadata&quot;][&quot;url&quot;].split(&quot;/&quot;)[-1].replace(&quot;.html&quot;, &quot;&quot;) or f&quot;page_{idx}&quot;<br>        )<br>        # Save markdown content<br>        if &quot;markdown&quot; in page:<br>            with open(f&quot;{output_dir}/{filename}.md&quot;, &quot;w&quot;) as f:<br>                f.write(page[&quot;markdown&quot;])</pre><p>Here is what the above function does:</p><ol><li>Creates an output directory if it doesn’t exist</li><li>Saves the complete crawl results as a JSON file with proper indentation</li><li>For each crawled page:</li></ol><ul><li>Generates a filename based on the page URL</li><li>Saves the markdown content to a separate .md file</li></ul><pre>app = FirecrawlApp()<br><br>crawl_result = app.crawl_url(url=&quot;https://docs.stripe.com/api&quot;, params={&quot;limit&quot;: 10})<br>save_crawl_results(crawl_result)</pre><p>It is a basic function that requires modifications for other scraping formats.</p><h4><strong>Database storage</strong></h4><p>For more complex applications, you might want to store the results in a database. Here’s an example using SQLite:</p><pre>import sqlite3<br><br>def save_to_database(crawl_result, db_path=&quot;crawl_results.db&quot;):<br>    conn = sqlite3.connect(db_path)<br>    cursor = conn.cursor()<br>    # Create table if it doesn&#39;t exist<br>    cursor.execute(<br>        &quot;&quot;&quot;<br>        CREATE TABLE IF NOT EXISTS pages (<br>            url TEXT PRIMARY KEY,<br>            title TEXT,<br>            content TEXT,<br>            metadata TEXT,<br>            crawl_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP<br>        )<br>    &quot;&quot;&quot;<br>    )<br>    # Insert pages<br>    for page in crawl_result[&quot;data&quot;]:<br>        cursor.execute(<br>            &quot;INSERT OR REPLACE INTO pages (url, title, content, metadata) VALUES (?, ?, ?, ?)&quot;,<br>            (<br>                page[&quot;metadata&quot;][&quot;url&quot;],<br>                page[&quot;metadata&quot;][&quot;title&quot;],<br>                page.get(&quot;markdown&quot;, &quot;&quot;),<br>                json.dumps(page[&quot;metadata&quot;]),<br>            ),<br>        )<br>    conn.commit()<br>    print(f&quot;Saved {len(crawl_result[&#39;data&#39;])} pages to {db_path}&quot;)<br>    conn.close()</pre><p>The function creates a SQLite database with a pages table that stores the crawled data. For each page, it saves the URL (as primary key), title, content (in markdown format), and metadata (as JSON). The crawl date is automatically added as a timestamp. If a page with the same URL already exists, it will be replaced with the new data. This provides a persistent storage solution that can be easily queried later.</p><pre>save_to_database(crawl_result)</pre><pre>Saved 9 pages to crawl_results.db</pre><p>Let’s query the database to double-check:</p><pre># Query the database<br>conn = sqlite3.connect(&quot;crawl_results.db&quot;)<br>cursor = conn.cursor()<br>cursor.execute(&quot;SELECT url, title, metadata FROM pages&quot;)<br>print(cursor.fetchone())<br>conn.close()</pre><pre>(<br>        &#39;https://docs.stripe.com/api/errors&#39;,<br>        &#39;Errors | Stripe API Reference&#39;,<br>        {<br>            &quot;url&quot;: &quot;https://docs.stripe.com/api/errors&quot;,<br>            &quot;title&quot;: &quot;Errors | Stripe API Reference&quot;, <br>            &quot;language&quot;: &quot;en-US&quot;,<br>            &quot;viewport&quot;: &quot;width=device-width, initial-scale=1&quot;,<br>            &quot;sourceURL&quot;: &quot;https://docs.stripe.com/api/errors&quot;,<br>            &quot;statusCode&quot;: 200,<br>            &quot;description&quot;: &quot;Complete reference documentation for the Stripe API. Includes code snippets and examples for our Python, Java, PHP, Node.js, Go, Ruby, and .NET libraries.&quot;,<br>            &quot;ogLocaleAlternate&quot;: []<br>        }<br>    )</pre><h4>Cloud storage</h4><p>For production applications, you might want to store results in cloud storage. Here’s an example using AWS S3:</p><pre>import boto3<br>from datetime import datetime<br><br>def save_to_s3(crawl_result, bucket_name, prefix=&quot;crawls&quot;):<br>    s3 = boto3.client(&quot;s3&quot;)<br>    timestamp = datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;)<br>    # Save full results<br>    full_results_key = f&quot;{prefix}/{timestamp}/full_results.json&quot;<br>    s3.put_object(<br>        Bucket=bucket_name,<br>        Key=full_results_key,<br>        Body=json.dumps(crawl_result, indent=2),<br>    )<br>    # Save individual pages<br>    for idx, page in enumerate(crawl_result[&quot;data&quot;]):<br>        if &quot;markdown&quot; in page:<br>            page_key = f&quot;{prefix}/{timestamp}/pages/{idx}.md&quot;<br>            s3.put_object(Bucket=bucket_name, Key=page_key, Body=page[&quot;markdown&quot;])<br>    print(f&quot;Successfully saved {len(crawl_result[&#39;data&#39;])} pages to {bucket_name}/{full_results_key}&quot;)</pre><p>Here is what the function does:</p><ul><li>Takes a crawl result dictionary, S3 bucket name, and an optional prefix as input</li><li>Creates a timestamped folder structure in S3 to organize the data</li><li>Saves the full crawl results as a single JSON file</li><li>For each crawled page that has markdown content, save it as an individual .md file</li><li>Uses boto3 to handle the AWS S3 interactions</li><li>Preserves the hierarchical structure of the crawl data</li></ul><p>For this function to work, you must have boto3 installed and your AWS credentials saved inside the ~/.aws/credentials file with the following format:</p><pre>[default]<br>aws_access_key_id = your_access_key<br>aws_secret_access_key = your_secret_key<br>region = your_region</pre><p>Then, you can execute the function provided that you already have an S3 bucket to store the data:</p><pre>save_to_s3(crawl_result, &quot;sample-bucket-1801&quot;, &quot;stripe-api-docs&quot;)</pre><pre>Successfully saved 9 pages to sample-bucket-1801/stripe-api-docs/20241118_142945/full_results.json</pre><h4>Incremental saving with async crawls</h4><p>When using async crawling, you might want to save results incrementally as they come in:</p><pre>import time<br><br>def save_incremental_results(app, crawl_id, output_dir=&quot;firecrawl_output&quot;):<br>    Path(output_dir).mkdir(parents=True, exist_ok=True)<br>    processed_urls = set()<br>    while True:<br>        # Check current status<br>        status = app.check_crawl_status(crawl_id)<br>        # Save new pages<br>        for page in status[&quot;data&quot;]:<br>            url = page[&quot;metadata&quot;][&quot;url&quot;]<br>            if url not in processed_urls:<br>                filename = f&quot;{output_dir}/{len(processed_urls)}.md&quot;<br>                with open(filename, &quot;w&quot;) as f:<br>                    f.write(page.get(&quot;markdown&quot;, &quot;&quot;))<br>                processed_urls.add(url)<br>        # Break if crawl is complete<br>        if status[&quot;status&quot;] == &quot;completed&quot;:<br>            print(f&quot;Saved {len(processed_urls)} pages.&quot;)<br>            break<br>        time.sleep(5)  # Wait before checking again</pre><p>Here is what the function does:</p><ul><li>Creates an output directory if it doesn’t exist</li><li>Maintains a set of processed URLs to avoid duplicates</li><li>Continuously checks the crawl status until completion</li><li>For each new page found, saves its markdown content to a numbered file</li><li>Sleeps for 5 seconds between status checks to avoid excessive API calls</li></ul><p>Let’s use it while the app crawls Books-to-Scrape website:</p><pre># Start the crawl<br>crawl_status = app.async_crawl_url(url=&quot;https://books.toscrape.com/&quot;)<br><br># Save results incrementally<br>save_incremental_results(app, crawl_status[&quot;id&quot;])</pre><pre>Saved 705 pages.</pre><h3>Building AI-Powered Web Crawlers with Firecrawl and LangChain Integration</h3><p>Firecrawl has integrations with popular open-source libraries like LangChain and other platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OfpsBmfdGh0DWmRS.png" /></figure><p>In this section, we will see how to use the LangChain integration to build a basic QA chatbot on the <a href="https://python.langchain.com/docs/integrations/providers/">LangChain Community Integrations</a> website.</p><p>Start by installing LangChain and its related libraries:</p><pre>pip install langchain langchain_community langchain_anthropic langchain_openai</pre><p>Then, add your ANTHROPIC_API_KEY and OPENAI_API_KEY as variables to your .env file.</p><p>Next, import the FireCrawlLoader class from the document loaders module and initialize it:</p><pre>from dotenv import load_dotenv<br>from langchain_community.document_loaders.firecrawl import FireCrawlLoader<br><br>load_dotenv()<br><br>loader = FireCrawlLoader(<br>    url=&quot;https://python.langchain.com/docs/integrations/providers/&quot;,<br>    mode=&quot;crawl&quot;,<br>    params={&quot;limit&quot;: 5, &quot;scrapeOptions&quot;: {&quot;onlyMainContent&quot;: True}},<br>)</pre><p>The class can read your Firecrawl API key automatically since we are loading the variables using load_dotenv().</p><p>To start the crawl, you can call the load() method of the loader object and the scraped contents will be turned into LangChain-compatible documents:</p><pre># Start the crawl<br>docs = loader.load()</pre><p>The next step is chunking:</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter<br><br># Add text splitting before creating the vector store<br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)<br># Split the documents<br>split_docs = text_splitter.split_documents(docs)</pre><p>Above, we split the documents into smaller chunks using the RecursiveCharacterTextSplitter. This helps make the text more manageable for processing and ensures better results when creating embeddings and performing retrieval. The chunk size of 1,000 characters with a 100-character overlap provides a good balance between context preservation and granularity.</p><pre>from langchain_chroma import Chroma<br>from langchain.embeddings import OpenAIEmbeddings<br>from langchain_community.vectorstores.utils import filter_complex_metadata<br><br># Create embeddings for the documents<br>embeddings = OpenAIEmbeddings()<br><br># Create a vector store from the loaded documents<br>docs = filter_complex_metadata(docs)<br>vector_store = Chroma.from_documents(docs, embeddings)</pre><p>Moving on, we create a vector store using Chroma and OpenAI embeddings. The vector store enables semantic search and retrieval on our documents. We also filter out complex metadata that could cause storage issues.</p><p>The final step is building the QA chain using Claude 3.5 Sonnet as the language model:</p><pre>from langchain.chains import RetrievalQA<br>from langchain_anthropic import ChatAnthropic<br><br># Initialize the language model<br>llm = ChatAnthropic(model=&quot;claude-3-5-sonnet-20240620&quot;, streaming=True)<br># Create a QA chain<br>qa_chain = RetrievalQA.from_chain_type(<br>    llm=llm,<br>    chain_type=&quot;stuff&quot;,<br>    retriever=vector_store.as_retriever(),<br>)</pre><p>Now, we can ask questions about our documents:</p><pre># Example question<br>query = &quot;What is the main topic of the website?&quot;<br>answer = qa_chain.invoke(query)<br><br>print(answer)</pre><pre>{<br>    &#39;query&#39;: &#39;What is the main topic of the website?&#39;,<br>    &#39;result&#39;: &quot;&quot;&quot;The main topic of the website is LangChain&#39;s integrations with Hugging Face. <br>    The page provides an overview of various LangChain components that can be used with <br>    Hugging Face models and services, including:<br>    1. Chat models<br>    2. LLMs (Language Models) <br>    3. Embedding models<br>    4. Document loaders<br>    5. Tools<br>    The page focuses on showing how to use different Hugging Face functionalities within <br>    the LangChain framework, such as embedding models, language models, datasets, and <br>    other tools.&quot;&quot;&quot;<br>}<br></pre><p>This section demonstrated a process for building a basic RAG pipeline for content scraped using Firecrawl. For this version, we only used 10 pages from the LangChain documentation. As the volume of information increases, the pipeline would need additional refinement. To scale this pipeline effectively, we would need to consider several factors including:</p><ul><li>Chunking strategy optimization</li><li>Embedding model selection</li><li>Vector store performance tuning</li><li>Prompt engineering for larger document collections</li></ul><h3>Conclusion</h3><p>Throughout this guide, we’ve explored Firecrawl’s /crawl endpoint and its capabilities for web scraping at scale. From basic usage to advanced configurations, we covered URL control, performance optimization, and asynchronous operations. We also examined practical implementations, including data storage solutions and integration with frameworks like LangChain.</p><p>The endpoint’s ability to handle JavaScript content, pagination, and various output formats makes it a versatile tool for modern web scraping needs. Whether you’re building documentation chatbots or gathering training data, Firecrawl provides a robust foundation. By leveraging the configuration options and best practices discussed, you can build efficient and scalable web scraping solutions tailored to your specific requirements.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a8940183c91" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/firecrawl-how-to-scrape-entire-websites-with-a-single-command-in-python-5a8940183c91">Firecrawl: How to Scrape Entire Websites With a Single Command in Python</a> was originally published in <a href="https://medium.datadriveninvestor.com">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Visualize Differentially Private Datasets in Matplotlib with Antigranular]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.datadriveninvestor.com/how-to-visualize-differentially-private-datasets-in-matplotlib-with-antigranular-c4ca7c0309ae?source=rss-39db050c2ac2------2"><img src="https://cdn-images-1.medium.com/max/600/1*hskkLa4rTzMkRuc-9XF6OQ.png" width="600"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.datadriveninvestor.com/how-to-visualize-differentially-private-datasets-in-matplotlib-with-antigranular-c4ca7c0309ae?source=rss-39db050c2ac2------2">Continue reading on DataDrivenInvestor »</a></p></div>]]></description>
            <link>https://medium.datadriveninvestor.com/how-to-visualize-differentially-private-datasets-in-matplotlib-with-antigranular-c4ca7c0309ae?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4ca7c0309ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[privacy]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 02:46:01 GMT</pubDate>
            <atom:updated>2024-07-20T07:20:52.869Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[A Foolproof Accountability System That Beat My Lifelong Procrastination]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/practice-in-public/a-foolproof-accountability-system-that-beat-my-lifelong-procrastination-36141cc7e996?source=rss-39db050c2ac2------2"><img src="https://cdn-images-1.medium.com/max/1368/1*vvstAISafTD2MoZSdceU2A.jpeg" width="1368"></a></p><p class="medium-feed-snippet">Lose real money for skipping habits</p><p class="medium-feed-link"><a href="https://medium.com/practice-in-public/a-foolproof-accountability-system-that-beat-my-lifelong-procrastination-36141cc7e996?source=rss-39db050c2ac2------2">Continue reading on Practice in Public »</a></p></div>]]></description>
            <link>https://medium.com/practice-in-public/a-foolproof-accountability-system-that-beat-my-lifelong-procrastination-36141cc7e996?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/36141cc7e996</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-development]]></category>
            <category><![CDATA[procrastination]]></category>
            <category><![CDATA[accountability]]></category>
            <category><![CDATA[self-improvement]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 08:05:42 GMT</pubDate>
            <atom:updated>2024-07-17T08:05:42.536Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Vizly: a Data Analysis Tool That Requires No Learning]]></title>
            <link>https://medium.datadriveninvestor.com/vizly-a-data-analysis-tool-that-requires-no-learning-ceb268710b9e?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ceb268710b9e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 02:06:10 GMT</pubDate>
            <atom:updated>2024-07-01T08:18:37.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>BI platform to analyze data in natural language</h4><h4>Introduction</h4><p>Business success depends on understanding your data, but complex BI tools can create a barrier to entry. That’s why Vizly was built — a platform that allows users to interact with their data sources in plain English. Vizly prioritizes data security and offers an on-premises solution, keeping all analyses entirely within your organization’s network.</p><p>On top of a familiar chat UI and data visualization capabilities, it has unique features such as chart and output editing, evaluating its own code, publishing analyses as standalone webpages and more. In this article, we will go over these features using the <a href="https://vizly.fyi/">web version of Vizly</a>.</p><h4>Setting up Vizly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*_d2MUHGT7ZIq9Mki.png" /><figcaption>Image by the author. Homepage of the Vizly website.</figcaption></figure><p>There is no complicated process to sign up for Vizly. Simply visit the <a href="https://vizly.fyi/">website</a> and click on “Get started for free”. Then, choose to login with Gmail, GitHub or by email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cb7SiTHrMrFAKfPs.png" /><figcaption>Image by the author</figcaption></figure><p>Afterward, you will be redirected to the chat UI which is similar to ChatGPT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*cq09uPOlkwEOGOOc.png" /><figcaption>Image by the author</figcaption></figure><p>Upload your dataset file and you are good to go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*244275eJFQHx3GBI.gif" /><figcaption>Image by the author</figcaption></figure><blockquote><em>Currently, Vizly specializes in Excel and JSON files but can operate on images, PDFs and many other file types. If you don’t find the file type you want, you can request other data formats such as database connections through the support email or by signing up for the enterprise version.</em></blockquote><p>After uploading a data source, we ask Vizly what it can do for us:</p><ul><li>Data summary</li><li>Data visualization</li><li>Correlation analysis</li><li>Price prediction — machine learning</li><li>Clustering</li></ul><p>Let’s see if Vizly is true to its word.</p><h4>Performing EDA with Vizly</h4><p>A good exploratory data analysis (EDA) workflow usually consists of the following steps:</p><ul><li>Printing general information (summary statistics, dataset shape, column names, etc.)</li><li>Data cleaning (structural errors, data quality checks, outlier detection and removal, etc.)</li><li>Univariate analysis (creating single-variable plots)</li><li>Bivariate analysis (plotting two variables against each other)</li><li>Multivariate analysis (creating plots with more than two variables)</li></ul><p>These steps can be executed in order or a cycle as needed.</p><h4>General information</h4><p>First, we will start by printing a few dataset attributes. So, paste the following prompt into the Vizly UI:</p><pre>Let&#39;s start with printing general information and summary statistics about the dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u7-pCb0cGuvFnCn6.gif" /><figcaption>Image by the author</figcaption></figure><p>Vizly prints dataset information and the 5-number summary for numeric features. Unlike ChatGPT or Jupyter notebooks, you will see two buttons for editing the input and output generated by Vizly. For example, let’s say we don’t want to display dataset information using the .info() method because it is unnecessarily detailed and instead, just the .shape attribute to print dataset dimensions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MoTouVdCiiOVpQxU.gif" /><figcaption>Image by the author</figcaption></figure><p>To accomplish this, you can highlight the section of the code to change and press “Ctrl + K”. Then, write the edited code and press “Accept and run”. The output should change immediately, as seen above.</p><p>Let’s also print the summary statistics for categorical columns as well. The code I have in mind is the following:</p><pre>df.describe(include=&#39;category&#39;)</pre><p>Let’s see if Vizly will use it:</p><pre>Print the summary statistics for categorical columns as well.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pHutVMzY9IqurmHQ.gif" /><figcaption>Image by the author</figcaption></figure><p>Both the input and output are as we expected. However, Vizly referred to categorical columns as object, which is the default data type for Pandas when it loads text columns. We want to change this column type to be the category data type for its smaller memory footprint and access to better text handling.</p><p>Let’s fix that along with any other data cleaning issues in the dataset.</p><h4>Data cleaning</h4><p>First, we will write the prompt to replace the object data type:</p><pre>Convert `object` data type to Pandas category.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*G0uGom9dgU7hoRyk.png" /><figcaption>Image by the author</figcaption></figure><p>Correct! Now, let’s check for missing data:</p><pre>Check for missing or incosistent data</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IO4MmXwdv00Qlyqs.png" /><figcaption>Image by the author</figcaption></figure><p>There are none. From a cursory look, I don’t see any other problems with the dataset, so let’s ask Vizly if it can spot some more:</p><pre>What kind of other data cleaning issues do you see in the dataset?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ep7-iDZ9niMGZKv0.gif" /><figcaption>Image by the author</figcaption></figure><p>It says that there are multiple rows with 0 values which don’t make sense for diamond measurements. Clearly, those are missing values marked with zeros. We can drop them along with any duplicate rows:</p><pre>Are there duplicates in the dataset? If so, remove those and the rows with 0 values you found above.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mQYtfbfpCipmiEQ4.gif" /><figcaption>Image by the author</figcaption></figure><p>Great, we got rid of any zero values and 146 duplicate rows.</p><h4>Handling outliers</h4><p>Outliers are one of the worst things that can affect the results of your analyses and machine learning models. Therefore, it is essential to detect them and if necessary, remove them from the dataset.</p><pre>Handle outliers in numerical columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*IiOON7-qIihiO8UZ.png" /><figcaption>Image by the author</figcaption></figure><p>Vizly chose the IQR method and removed more than 6000 outliers. The method marks any data point as an outlier using the following steps:</p><ol><li>Find the first and third quartiles (25th and 75th percentiles) of the dataset — Q1 and Q3.</li><li>Find the inter-quartile range: Q3 — Q1.</li><li>Calculate the lower and upper bounds as shown in the code snippet above.</li><li>Mark any point as outlier if it is beyond the found bounds.</li></ol><p>The disadvantage of the IQR method is that it detects univariate outliers. In complex datasets, this isn’t usually good idea because outliers usually are multivariate. This means that value A may look like an outlier on its own but if you look at the row on the whole, it may not be anomalous. However, we have a toy dataset in our hands so, the IQR method will suffice.</p><p>If you want, you can ask Vizly to run Isolation Forest algorithm on the dataset through Scikit-learn. With Isolation Forest, you can control what percentage of the most outlying points you want to detect.</p><h4>Univariate analysis</h4><p>Now, let’s start creating some plots:</p><pre>Visualize the distribution of numerical columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*55FmqBjWYXmZFeH_.gif" /><figcaption>Image by the author</figcaption></figure><p>It looks like the default plotting library used in Vizly is Plotly. To see the distribution of each numeric feature, Vizly is using histograms. On the surface, the code to generate histograms looks ordinary. However, if you pay attention to the title of the last three histograms, you will see something clever — instead of saying “Distribution of X”, Vizly writes “Distribution of X dimension” all on its own. X, Y, Z are column names in the dataset and if Vizly simply wrote “Distribution of X/Y/Z”, it would be confusing for many.</p><p>Another unique feature of Vizly is the feature to edit charts once they have been created. Using the Edit chart button, you can change nearly any aspect of visuals, from the chart type itself to formatting of the tick marks. Below, I am modifying the title of the plot to make it more visually appealing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ig-f04yY3qNljsh7.gif" /><figcaption>Image by the author</figcaption></figure><h4>Bivariate analysis</h4><p>Bivariate analysis is where you perform tasks like plotting correlation matrix or numeric versus categorical boxplots:</p><pre>Analyze the correlation between numerical columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*49gi_JI3iTI1RkQn.gif" /><figcaption>Image by the author</figcaption></figure><p>The prompt only calculates the correlation matrix but doesn’t plot it. So, click on the “Continue analysis” button at the bottom:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*fumPQznhAsFwfyio.png" /><figcaption>Image by the author</figcaption></figure><p>Vizly correctly guesses the next step, which is creating a heatmap on the correlation matrix. This plot isn’t as nice looking as it would have been if plotted with Seaborn but it is good enough to see the general trends.</p><p>Now, let’s see the relationship between each numeric feature and the cut categories of diamonds. We are specifically telling Vizly to use Matplotlib since Plotly has lousy support for subplots:</p><pre>Plot the relationship between each numeric feature and the diamond cut categories using Matplotlib subplots</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5kn8vvye1LKn7t2V.gif" /><figcaption>Image by the author</figcaption></figure><p>Let’s ask Vizly to interpret the subplots:</p><pre>What do you make of these subplots?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1FGKvdMfR9OvIlS2.png" /><figcaption>Image by the author</figcaption></figure><p>All insights are spot-on (not to mention the fact that we reached them in a very short amount of time). I will leave it to you see the relationships among numeric features and the other two categorical columns.</p><h4>Multivariate analysis</h4><p>For multivariate analysis, we will content with plotting a pair-plot of all features colored with the diamond cut quality (this should take a moment to run):</p><pre>Plot a pair-plot of numeric features with category for color using Seaborn and Matplotlib</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*es6pWaqeGv0cwiob.gif" /><figcaption>Image by the author</figcaption></figure><p>You can try to find interesting trends/patterns yourself or you can ask Vizly again.</p><h4>Feature engineering</h4><p>Let’s see if Vizly can generate any new features for us to help with machine learning steps in the future:</p><pre>Based on your analysis, what kind of new features can you generate for the dataset?</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*oFTFgSakztF3T1f9.png" /><figcaption>Image by the author</figcaption></figure><p>Awesome — Vizly suggests six new features. The last three are simply ordinal encodings of the categorical columns but the first three are gold. Let’s tell Vizly to add them to the data frame:</p><pre>Add all of these new features to the dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*8roIsN6LlY7BwSBr.png" /><figcaption>Image by the author</figcaption></figure><h4>Wrapping up an analysis</h4><p>Once you are done with EDA and data cleaning, you can ask Vizly to download the final dataset:</p><pre>Let me download the final dataset</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xZWheZdJ7DzyQsr8.gif" /><figcaption>Image by the author</figcaption></figure><p>The data will be available to download as a file and it will also appear in your “Data” tab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*RsEPWxQBR70Ns4pv.png" /><figcaption>Image by the author</figcaption></figure><p>From there, you can launch a new conversation thread on the cleaned dataset to perform other types of analysis or even run some machine learning models.</p><p>After everything is done, you can download the entire conversation as PDF or a Jupyter Notebook by using the Export button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*J07g6x3WYGmC_RNn.png" /><figcaption>Image by the author</figcaption></figure><p>Or even better, you can share the thread as a standalone web page by clicking the Publish button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/0*J7DjgCFj_ukpCLXM.png" /><figcaption>Image by the author</figcaption></figure><p>Users will be able to duplicate or rerun the notebook from the link alone:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/0*k7yDH9jl2QsHdHbE.png" /><figcaption>Image by the author</figcaption></figure><h4>Data analyst vs. Vizly</h4><p>Ever since ChatGPT became more capable of data analysis, people have been predicting the death of the data analyst job. I think that is an incorrect presumption.</p><p>The job of data analyst is to find trends and insights in the ocean of data and communicate them effectively to their colleagues and project stakeholders. The focus is on the insights themselves, not how the data analyst found them. As far as fast results are concerned, most wouldn’t care about whether data analysts used the cool new Python framework or an AI platform. So, tools like <a href="http://vizly.fyi/">Vizly</a> should be seen as enhancements to the workflow of data analysts, not as their replacements.</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ceb268710b9e" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/vizly-a-data-analysis-tool-that-requires-no-learning-ceb268710b9e">Vizly: a Data Analysis Tool That Requires No Learning</a> was originally published in <a href="https://medium.datadriveninvestor.com">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Explore and Clean Sensitive Data You Can’t Even See With Antigranular]]></title>
            <link>https://medium.datadriveninvestor.com/how-to-explore-and-clean-sensitive-data-you-cant-even-see-with-antigranular-14efca3cfcae?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/14efca3cfcae</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 07:33:43 GMT</pubDate>
            <atom:updated>2024-03-05T05:53:01.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>Working with differentially private data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_isgHj1rJjQPZPNUdYDDwA.jpeg" /><figcaption>Image by author via Leonardo AI</figcaption></figure><h4>Motivation</h4><p>Differential privacy is a powerful framework to work with highly sensitive data such as PII (personal identification information), financial data, health information, biometric data and so on. When data science and machine learning methods are used on these datasets under differential privacy, there is virtually no chance of extracting individual details from any row.</p><p>The framework ensures high security by requiring the use of specific functions and algorithms that support differential privacy. However, this requirement limits the use of many Python libraries that are not designed with these privacy standards in mind.</p><p>Antigranular offers a solution to address this limitation. It is a platform designed to facilitate “eyes-off data science” within the framework of differential privacy. This tutorial will guide you through the process of conducting Exploratory Data Analysis (EDA) and cleaning data on a sample dataset using Antigranular while adhering to privacy requirements.</p><h4>What is Antigranular?</h4><p>I’ve discussed the Antigranular platform in-depth in a <a href="https://medium.com/towards-artificial-intelligence/antigranular-how-to-access-sensitive-datasets-without-looking-at-them-44090cb22d8a">previous article</a>. So, we will only summarize the main points here as understanding them is a requirement for this article.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*TzIbcXCoXCg9-JGLMxBuwQ.png" /><figcaption>Homepage of AntiGranular</figcaption></figure><p>Antigranular is a secure platform for any company to host their sensitive datasets under differential privacy. The platform stores datasets using <a href="https://aws.amazon.com/ec2/nitro/nitro-enclaves/">AWS Nitro Enclaves</a> that leverage cryptographic attestation for security. Then, the data is exposed to the public through authentication.</p><p>Anyone will be able to use the data but can’t actually look at individual rows. This raises the question — why share data that people can’t see?</p><p>Well, Antigranular isn’t just a secure storage — it is a Kaggle-like competition platform where users compete to solve machine learning tasks using DP datasets and methods. It also allows users to share their solutions publicly in notebooks just like in Kaggle.</p><figure><img alt="image.png" src="https://cdn-images-1.medium.com/proxy/1*PDR5xUKn_Os1vRo1Pw2l1Q.png" /><figcaption>Competitions page of Antigranular</figcaption></figure><p>To use differentially private libraries and datasets locally, Antigranular comes with a Python library in the same name. Today, we will use all of these to perform a typical EDA on the DP version of the open-source <a href="https://www.kaggle.com/datasets/shivam2503/diamonds">Diamonds dataset</a>.</p><p>To learn more about Antigranular, please read my <a href="https://medium.com/towards-artificial-intelligence/antigranular-how-to-access-sensitive-datasets-without-looking-at-them-44090cb22d8a">last post</a>.</p><h4>Setup</h4><p>We start the EDA by connecting to the DP Diamonds dataset available on <a href="https://www.antigranular.com/datasets/65cb18fe5f09c08e900036c2">this page of Antigranular (AG)</a>. If you already signed up for the platform, each dataset page will display a snippet that shows how to connect to the Nitro Enclave containing the dataset. Please, copy it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*1IKjcajA45qQQuky5qMCfw.gif" /><figcaption>The diamonds dataset page of Antigranular</figcaption></figure><p>Then, spin up a local Jupyter session and run the snippet you just copied:</p><pre>import antigranular as ag  # pip install antigranular<br><br>session = ag.login(<br>    &quot;*****************&quot;,<br>    &quot;******************************&quot;,<br>    dataset=&quot;Diamonds Dataset&quot;,<br>)</pre><pre>[OUT]:<br><br>....<br>Cell magic &#39;%%ag&#39; registered successfully, use `%%ag` in a notebook cell to execute your python code on Antigranular private python server<br>🚀 Everything&#39;s set up and ready to roll!</pre><p>If the login is successful, you will get a message that says the dataset has been loaded as diamonds_dataset and that the %%ag cell magic has been registered into your environment.</p><p>From this point on, your Jupyter session is connected to two machines (servers): your own local machine and the Nitro enclave of Antigranular.</p><p>If your cell starts with the %%ag cell magic, the next lines of code will be run on the enclave. It comes with a DP version of Python and a few differentially private and some regular open-source libraries of the data stack already installed.</p><p>This means that if you want to perform any operation on diamonds_dataset, it must be inside a cell with %%ag magic:</p><pre>%%ag<br><br>train_X = diamonds_dataset[&quot;train_x&quot;]<br>train_y = diamonds_dataset[&quot;train_y&quot;]</pre><p>The above code extracts the feature and target arrays from the diamonds_dataset variable inside the enclave. If you run it without the magic, you will get a name error because the code won’t be run inside the enclave:</p><pre>train_X = diamonds_dataset[&quot;train_x&quot;]<br>train_y = diamonds_dataset[&quot;train_y&quot;]<br><br>-------------<br><br>NameError: name &#39;diamonds_dataset&#39; is not defined</pre><p>train_X and train_y are instances of PrivateDataFrame class included in the op_pandas library:</p><pre>%%ag<br><br>from op_pandas import PrivateDataFrame, PrivateSeries</pre><p>op_pandas is a smaller version of Pandas that contains differentially private functions and methods. Columns in private dataframes are represented by PrivateSeries.</p><h4>1. Looking at the data</h4><p>We can’t look at the actual rows because of DP but we have other methods to get a feel for the dataset, starting with column names:</p><pre>%%ag<br><br># Print the columns of the dataset<br>ag_print(&quot;Columns: \n&quot;, train_X.columns)</pre><pre>Columns: <br> [&#39;carat&#39;, &#39;cut&#39;, &#39;color&#39;, &#39;clarity&#39;, &#39;depth&#39;, &#39;table&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;]</pre><p>Then, we can print the data type of each column above:</p><pre>%%ag<br><br>ag_print(&quot;Dtypes: \n&quot;, train_X.dtypes)</pre><pre>Dtypes: <br> carat      float64<br>cut         object<br>color       object<br>clarity     object<br>depth      float64<br>table      float64<br>x          float64<br>y          float64<br>z          float64<br>dtype: object</pre><p>The data types are mostly correctly assigned (the object data type is not ideal for string columns).</p><p>Now, let’s look at the 5-number summary of the dataset, which will tell us the standard deviation, mean, median and percentiles of each numeric column:</p><pre>%%ag<br><br>results = train_X.describe(eps=1)<br><br>ag_print(results)</pre><pre>carat         depth  ...             y             z<br>count  37717.000000  37728.000000  ...  37731.000000  37746.000000<br>mean       0.804813     61.806690  ...      5.616625      3.562508<br>std        0.443778      1.825406  ...      1.874300      2.116515<br>min        0.200000     43.000000  ...      0.000000      0.000000<br>25%        0.439432     60.489722  ...      4.964873      2.804861<br>50%        0.709064     61.770117  ...      5.688359      3.618784<br>75%        0.983109     63.112093  ...      6.425548      3.778991<br>max        4.802821     68.814405  ...     41.519457     30.588921<br><br>[8 rows x 6 columns]</pre><p>The 5-number summary is calculated using describe but as you must have noticed, this version of describe has a parameter called eps. The new parameter stands for <em>epsilon</em>, which controls the level of deliberate noise injected into each calculation. It ranges from 0 to infinity but typically stays in the 1-5 range depending on the function used.</p><p>As you might guess, epsilon is an important parameter of differential privacy. At the beginning of each session, you start with a large epsilon budget. The more you use it, the less private and secure your code becomes. So, you have to strike the balance between epsilon and usability. If you use too much epsilon, your code becomes less differentially private whereas, being too strict with epsilon may introduce way too much noise in your calculation and make it useless.</p><p>To see how close describe with one epsilon is to the actual 5-number summary of the Diamonds dataset, we will compare it to the open-source version. But that comparison can only be made locally, outside the Nitro enclave. So, what can we do?</p><p>When you need the results of computations locally, AG allows you to export them from the enclave:</p><pre>%%ag<br><br>export(results, name=&quot;results&quot;)</pre><pre>Setting up exported variable in local environment: results</pre><p>The syntax is very simpe. The above code loads the results of the 5-number summary into our local Jupyter session:</p><pre>print(results)</pre><pre>carat         depth         table             x             y  \<br>count  37717.000000  37728.000000  37773.000000  37776.000000  37731.000000   <br>mean       0.804813     61.806690     57.529598      5.707087      5.616625   <br>std        0.443778      1.825406      3.693945      0.943331      1.874300   <br>min        0.200000     43.000000     43.000000      0.000000      0.000000   <br>25%        0.439432     60.489722     55.876997      4.616063      4.964873   <br>50%        0.709064     61.770117     56.564244      5.604013      5.688359   <br>75%        0.983109     63.112093     57.936230      6.825518      6.425548   <br>max        4.802821     68.814405     79.931229     10.119966     41.519457   <br><br>                  z  <br>count  37746.000000  <br>mean       3.562508  <br>std        2.116515  <br>min        0.000000  <br>25%        2.804861  <br>50%        3.618784  <br>75%        3.778991  <br>max       30.588921</pre><p>Now, to compare results with the actual 5-number summary, we will load the Diamonds dataset through Seaborn and call describe:</p><pre>import seaborn as sns<br><br>diamonds = sns.load_dataset(&quot;diamonds&quot;)<br>results_local = diamonds.describe()</pre><p>To find the differences, we just subtract results_local from results:</p><pre>results - results_local</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*sMvT7i31mFoyO5kOa3Y6tA.png" /></figure><p>As you can see, for almost all metrics, the differences are marginal, which means we used the right amount of epsilon.</p><p>There are other statistical functions supported in op_pandas, like .percentile. Let&#39;s use it to find the minimum and maximum of the target (diamond prices):</p><pre>%%ag<br><br>price_min = train_y.percentile(eps=0.1, p=0)<br>price_max = train_y.percentile(eps=0.1, p=100)<br><br>ag_print(price_min)<br>ag_print(price_max)</pre><pre>price    345.430128<br>dtype: float64<br>price    18490.061918<br>dtype: float64</pre><p>percentile also accepts epsilon and additionally, the percentile parameter p. Let&#39;s compare this with the actual minimum and maximum of diamond prices:</p><pre>diamonds.price.min()</pre><pre>326</pre><pre>diamonds.price.max()</pre><pre>18823</pre><p>We are close but close enough. Let’s increase epsilon and see what happens:</p><pre>%%ag<br><br>price_min = train_y.percentile(eps=0.2, p=0)<br>price_max = train_y.percentile(eps=0.2, p=100)<br><br>ag_print(price_min)<br>ag_print(price_max)</pre><pre>price    333.53453<br>dtype: float64<br>price    18815.210025<br>dtype: float64</pre><p>We got even closer! But keep in mind that when you are working with real-world DP datasets, you won’t have any means of checking whether you set the right amount of epsilon. Getting a hang of this parameter comes through practice and experience.</p><h4>2. Cleaning data</h4><p>Diamonds dataset is relatively clean, so there isn’t much to do in this section. But in any case, data cleaning starts with copying the data so that you won’t mess it up accidentally. Like in pandas, op_pandas has .copy function:</p><pre>%%ag<br><br>train_X_copy = train_X.copy()<br>train_y_copy = train_y.copy()</pre><p>The next common operation in cleaning is dropping unnecessary columns. For example, when loading CSVs, you might have come across the Column: 0 column, which is for index:</p><pre>%%ag<br><br># Hypothetical<br>train_X.drop(columns=&quot;Column: 0&quot;, inplace=True)  # Default</pre><p>Dropping columns is the same in Pandas and there is no need to spend epsilon. You can also drop missing values without epsilon:</p><pre>%%ag<br><br>train_X.dropna(axis=0)  # Across the rows</pre><p>Another common operation is renaming columns. Here is how to rename “price” to “target”:</p><pre>%%ag<br><br>ag_print(train_y.columns)</pre><pre>[&#39;price&#39;]</pre><pre>%%ag<br><br>renamed_target = train_y_copy.rename({&quot;price&quot;: &quot;target&quot;})<br><br>ag_print(renamed_target.columns)</pre><pre>[&#39;target&#39;]</pre><p>rename doesn’t use epsilon either.</p><h4>3. Selecting data</h4><p>Retrieving and subsetting necessary parts of datasets is pretty common. For example, you can use the familiar brackets notation to select columns:</p><pre>%%ag<br><br>ag_print(train_X[&quot;cut&quot;].count(eps=0.1))</pre><pre>37720</pre><p>Above, we are printing the number of rows of the cut column using count, which accepts epsilon. It is also possible to select multiple columns:</p><pre>%%ag<br><br>selected_cols = train_X[[&quot;cut&quot;, &quot;color&quot;]]<br><br>ag_print(&quot;Selected columns:\n&quot;, selected_cols.columns)</pre><pre>Selected columns:<br> [&#39;cut&#39;, &#39;color&#39;]</pre><p>It is also possible to filter (select) the data based on a condition. For example, we can filter the dataset for diamonds with half a carat or less:</p><pre>%%ag<br><br># Filter for diamonds below half a carat<br>low_carat = train_X.where(train_X[&quot;carat&quot;] &lt; 0.5)<br><br>ag_print(low_carat.count(eps=0.1))</pre><pre>carat      12252<br>cut        12434<br>color      12308<br>clarity    12355<br>depth      12263<br>table      12243<br>x          12371<br>y          12278<br>z          12471<br>dtype: int64</pre><p>The condition is specified inside the where function, which doesn’t require epsilon. You can also chain conditions with | (or) and &amp; (and) operators. Below, we will choose diamonds with carat below 0.5 and depth over 65:</p><pre>%%ag<br><br>temp = train_X.where((train_X[&quot;carat&quot;] &lt; 0.5) &amp; (train_X[&quot;depth&quot;] &gt; 65))<br>ag_print(temp.count(eps=0.1))</pre><pre>carat      154<br>cut          0<br>color      164<br>clarity     95<br>depth        0<br>table        3<br>x           61<br>y           36<br>z            0<br>dtype: int64</pre><p>Some of the columns have a count of 0, which suggest that there might be no diamonds matching our condition.</p><p>Let’s do a final filter for diamonds with carat over three:</p><pre>%%ag<br><br># Filter for diamonds above three carats<br>high_carat = train_X.where(train_X[&quot;carat&quot;] &gt; 3)<br><br>ag_print(high_carat.count(eps=0.1))</pre><pre>carat        0<br>cut        105<br>color      347<br>clarity    229<br>depth        0<br>table       52<br>x            0<br>y            0<br>z            0<br>dtype: int64</pre><h4>4. Joining data in Antigranular</h4><p>In actual projects, you will have to join multiple datasets to start your analysis. For example, imagine that the above diamonds dataset were given to you in two chunks: low_carat and high_carat.</p><p>Creating a single larger dataset with rows from both, you can use concat of op_pandas:</p><pre>%%ag<br>import op_pandas as opd<br><br># Doesn&#39;t require epsilon<br>concatenated_diamonds = opd.concat([low_carat, high_carat])<br><br>ag_print(concatenated_diamonds.columns)<br>ag_print(concatenated_diamonds.count(eps=0.1))</pre><pre>[&#39;carat&#39;, &#39;cut&#39;, &#39;color&#39;, &#39;clarity&#39;, &#39;depth&#39;, &#39;table&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;]<br><br>carat      12464<br>cut        12383<br>color      12315<br>clarity    12377<br>depth      12386<br>table      12341<br>x          12461<br>y          12507<br>z          12325<br>dtype: int64</pre><p>concat function takes a list of arrays to concatenate vertically, i.e. put on top of one another. The requirement is that the arrays have the same number of columns and names.</p><p>To concatenate datasets horizontally, so that they are put side-by-side, you can use the join function but we will take a look at it later.</p><h4>5. Looping functions</h4><p>Since looping involves accessing individual values of sequences, it is not allowed in differential privacy. However, there are some workarounds.</p><p>For example, the applymap function can be used to run a certain function across the entire PrivateDataFrame:</p><pre>%%ag<br><br><br>def absolute(x: int | float) -&gt; float:<br>    return abs(x)<br><br><br>num_cols = train_X[[&quot;carat&quot;, &quot;x&quot;, &quot;y&quot;, &quot;z&quot;, &quot;depth&quot;]]<br>num_cols_abs = num_cols.applymap(absolute, eps=1)<br><br>ag_print(num_cols_abs.count(eps=0.1))</pre><pre>carat    37751<br>x        37677<br>y        37726<br>z        37709<br>depth    37897<br>dtype: int64</pre><p>Above, we are running the absolute function over all numeric values in train_X. Since this is a large operation, we are using an eps of 1.</p><p>To apply a certain function to only one column, you can use map. For example, the below function will clip diamond carats to be three when they exceed that amount:</p><pre>%%ag<br>import numpy as np<br><br><br>def clip(x: float) -&gt; float:<br>    if x &lt; 3:<br>        return x<br>    return 3.0<br><br><br>train_X_copy[&quot;carat&quot;] = train_X_copy[&quot;carat&quot;].map(clip, eps=0.3)</pre><p>Keep in mind that both applymap and map require functions with type annotations both for parameter and return values.</p><h4>6. Plotting a histogram in Antigranular</h4><p>Now, we get to the fun part — visualizations. Due to the nature of DP, our fun will be a bit limited but at least, we get to plot a few graphs. So, let’s start with histograms.</p><p>Private data frames don’t have the .plot method like pandas, which automatically figures out the bins, bin heights and widths. But in op_pandas, we have to do them manually. Fortunately, there is the .hist function for that:</p><pre>%%ag<br><br># The default number of bins is 10<br>hist_data = train_y_copy.hist(column=&quot;price&quot;, eps=0.1, bins=10)<br>export(hist_data, &quot;hist_data&quot;)</pre><pre>Setting up exported variable in local environment: hist_data</pre><p>We are calculating a histogram for price and exporting the results locally to plot with Matplotlib.</p><p>In the local session, we import the necessary modules and extract the histogram components into bin_heights and bin_x. Then, we pass them in the exact order shown to plt.bar function:</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br><br># Extract the bin locations and heights<br>bin_heights, bin_x = hist_data<br><br># Create a histogram with plt.bar<br>plt.bar(bin_x[:-1], bin_heights, width=np.diff(bin_x) * 0.8, align=&quot;edge&quot;)<br><br>plt.xlabel(&quot;Price ($)&quot;)<br>plt.ylabel(&quot;Count&quot;)<br>plt.title(&quot;The distribution of diamond prices&quot;)<br><br># Display the plot<br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*yvaq79jzrHAe-osfC3U38A.png" /></figure><p>The histogram shows that most of the diamonds are priced below 5000$.</p><p>We can also plot a 2D histogram which allows to see the overlap between two numeric features, like price and carat.</p><p>Right now, the price column is in train_y while the carat is in train_X, which means we have to join the two arrays horizontally. Remember the join function?</p><pre>%%ag<br># Concatenate X and y arrays<br>diamonds_full = train_X.join(train_y, how=&quot;outer&quot;)<br><br># Create a 2D histogram<br>hist2d = diamonds_full.hist2d(x=&quot;price&quot;, y=&quot;carat&quot;, eps=0.3, bins=15)<br># Export locally<br>export(hist2d, &quot;hist2d&quot;)</pre><pre>Setting up exported variable in local environment: hist2d</pre><p>join actually performs an SQL-style join, and when you set its how argument to outer, it will put the arrays side-by-side. Then, we can run the hist2d function on the resulting array, specifying the two numeric columns we want and the number of bins. Then, we export the result locally.</p><p>This time, the histogram has three components, which we extract into h, xbins and ybins below. Then, we pass these in the exact order as shown into matshow function. We also make sure to capture the result of matshow into cax so that we can add a colorbar later:</p><pre>fig, ax = plt.subplots(figsize=(8, 6))<br><br># Extract the 2D histogram components<br>h, xbins, ybins = hist2d<br><br># Plot the histogram<br>cax = ax.matshow(h, extent=[xbins[0], xbins[-1], ybins[-1], ybins[0]], aspect=&quot;auto&quot;)<br>ax.set(title=&quot;Price vs. carat 2D histogram&quot;, xlabel=&quot;Price&quot;, ylabel=&quot;Carat&quot;)<br># Add a colorbar<br>plt.colorbar(cax, ax=ax)<br><br>plt.show()</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*44vl0H6pNBIs_g6S6hzfcA.png" /></figure><p>The 2D histogram shows that the majority of diamonds (the top left corner) have low carats and low prices accordingly.</p><h4>7. Plotting a correlation matrix in Antigranular</h4><p>It is also possible to plot a correlation matrix in Antigranular and the workflow is very similar to how you used to do it in Pandas.</p><p>First, we calculate the matrix using corr and export the results locally. Make sure to use a higher epsilon:</p><pre>%%ag<br><br>corr_matrix = diamonds_full.corr(eps=5)<br>export(corr_matrix, &quot;corr_matrix&quot;)</pre><pre>Setting up exported variable in local environment: corr_matrix</pre><p>Afterwards, we do some preprocessing on the matrix such as filling in missing values (introduced due to noise) and forcing the range of correlations between 0 and 1. Finally, we pass the matrix to the heatmap function of Seaborn with some parameters for aesthetics:</p><pre># Pre-process<br>corr_matrix = corr_matrix.fillna(0)<br>corr_matrix = corr_matrix.clip(0, 1)<br><br>sns.heatmap(corr_matrix, center=0, fmt=&quot;.3f&quot;, square=True, annot=True, linewidth=0.3);</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*wRb9ku_UrgKJAvbddRcGuw.png" /></figure><p>We have got a beautiful looking heatmap!</p><h4>8. Plotting a scatterplot in Antigranular</h4><p>Technically, scatterplots are strictly not allowed in differential privacy but there is a workaround we can use.</p><p>By plotting multiple percentiles of two numeric features, we can plot their scatterplot that will display their general trend. The caveat here is that the operation will use too much epsilon. Since this is a non-production project, we can afford the cost.</p><p>We start by creating an array of 100 numbers, from 0 to 1 as percentiles.</p><pre>%%ag<br><br>import numpy as np<br><br>xs = np.arange(0, 1, 0.01)<br>percentiles_price = []<br>percentiles_carat = []</pre><p>Then, we create two arrays to store the result of each percentile.</p><p>Inside a loop, we calculate each percentile value of carat and price and add the results to the appropriate lists.</p><pre>%%ag<br><br>for x in xs:<br>    carat = train_X[&quot;carat&quot;].percentile(x, eps=0.1)<br>    price = train_y[&quot;price&quot;].percentile(x, eps=0.1)<br><br>    percentiles_carat.append(carat)<br>    percentiles_price.append(price)</pre><p>In the end, we have two arrays with equal length, each element denoting nth percentile of their distributions.</p><p>The next step is exporting the lists locally:</p><pre>%%ag<br><br>export(percentiles_price, &quot;prices&quot;)<br>export(percentiles_carat, &quot;carats&quot;)</pre><pre>Setting up exported variable in local environment: prices<br>Setting up exported variable in local environment: carats</pre><p>Finally, we can use the scatterplot function of Seaborn to create a reasonably good-looking scatterplot:</p><pre>ax = sns.scatterplot(x=prices, y=carats)<br><br>ax.set(title=&quot;Price vs. Carat of diamonds&quot;, xlabel=&quot;Price&quot;, ylabel=&quot;Carat&quot;)<br>plt.show();</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*DVx4s-BcTQoUZyugel4Zwg.png" /></figure><p>Since this is a non-traditional approach to scatterplots, we need to verify that it can actually capture the trend between these two variables. Let’s perform the same operation above for the open-source Diamonds dataset:</p><pre>import numpy as np<br><br>xs = np.arange(0, 1, 0.01)<br>percentiles_price = []<br>percentiles_carat = []<br><br>for x in xs:<br>    carat = diamonds[&quot;carat&quot;].quantile(x)<br>    price = diamonds[&quot;price&quot;].quantile(x)<br><br>    percentiles_carat.append(carat)<br>    percentiles_price.append(price)</pre><p>The only difference here is that we are using the quantile function, which is equivalent to percentile in Pandas. Now, we plot again:</p><pre>ax = sns.scatterplot(x=prices, y=carats)<br><br>ax.set(title=&quot;Price vs. Carat of diamonds&quot;, xlabel=&quot;Price&quot;, ylabel=&quot;Carat&quot;)<br>plt.show();</pre><figure><img alt="png" src="https://cdn-images-1.medium.com/proxy/1*DVx4s-BcTQoUZyugel4Zwg.png" /></figure><p>As we can see, the two plots are very similar to each other. The only problem is that we ended up spending 10 epsilon from our budget. Ouch!</p><h4>Conclusion</h4><p>Despite its limitations, differential privacy has massive applications in sectors such as government, finance and healthcare. It is still a developing technology and one of the best parties that are driving this growth is <a href="https://www.antigranular.com/">Antigranular</a>.</p><p>Today, we covered how to use the Python API of Antigranular and learned how to perform EDA on a differentially private dataset. Be sure to check out the ongoing and upcoming competitions on the platform and try to participate.</p><p>Thank you for reading!</p><p>Visit us at <a href="https://www.datadriveninvestor.com/"><em>DataDrivenInvestor.com</em></a></p><p>Subscribe to DDIntel <a href="https://www.ddintel.com/"><em>here</em></a>.</p><p>Have a unique story to share? Submit to DDIntel <a href="https://datadriveninvestor.com/ddintelsubmission"><em>here</em></a>.</p><p>Join our creator ecosystem <a href="https://join.datadriveninvestor.com/"><em>here</em></a>.</p><p><a href="https://ddintel.datadriveninvestor.com/"><em>DDIntel</em> </a>captures the more notable pieces from our <a href="https://www.datadriveninvestor.com/"><em>main site</em></a> and our popular <a href="https://medium.datadriveninvestor.com/"><em>DDI Medium publication</em></a>. Check us out for more insightful work from our community.</p><p>DDI Official Telegram Channel: <a href="https://t.me/+tafUp6ecEys4YjQ1">https://t.me/+tafUp6ecEys4YjQ1</a></p><p>Follow us on <a href="https://www.linkedin.com/company/data-driven-investor"><em>LinkedIn</em></a>, <a href="https://twitter.com/@DDInvestorHQ"><em>Twitter</em></a>, <a href="https://www.youtube.com/c/datadriveninvestor"><em>YouTube</em></a>, and <a href="https://www.facebook.com/datadriveninvestor"><em>Facebook</em></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14efca3cfcae" width="1" height="1" alt=""><hr><p><a href="https://medium.datadriveninvestor.com/how-to-explore-and-clean-sensitive-data-you-cant-even-see-with-antigranular-14efca3cfcae">How to Explore and Clean Sensitive Data You Can’t Even See With Antigranular</a> was originally published in <a href="https://medium.datadriveninvestor.com">DataDrivenInvestor</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Antigranular: How to Access Sensitive Datasets Without Looking At Them]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://pub.towardsai.net/antigranular-how-to-access-sensitive-datasets-without-looking-at-them-44090cb22d8a?source=rss-39db050c2ac2------2"><img src="https://cdn-images-1.medium.com/max/1024/1*bSF8a73YIH1fi1KhEvRlhA.jpeg" width="1024"></a></p><p class="medium-feed-snippet">and develop privacy-first data projects</p><p class="medium-feed-link"><a href="https://pub.towardsai.net/antigranular-how-to-access-sensitive-datasets-without-looking-at-them-44090cb22d8a?source=rss-39db050c2ac2------2">Continue reading on Towards AI »</a></p></div>]]></description>
            <link>https://pub.towardsai.net/antigranular-how-to-access-sensitive-datasets-without-looking-at-them-44090cb22d8a?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/44090cb22d8a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Fri, 22 Dec 2023 22:01:38 GMT</pubDate>
            <atom:updated>2023-12-22T22:01:38.074Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Pandas cut vs. qcut Explained Clearly (Finally)]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://pub.towardsai.net/pandas-cut-vs-qcut-explained-clearly-finally-905847d473bd?source=rss-39db050c2ac2------2"><img src="https://cdn-images-1.medium.com/max/2600/1*TQvPD97gnS1aPlVd5bXvmg.jpeg" width="4608"></a></p><p class="medium-feed-snippet">How to customarily bin data in Pandas</p><p class="medium-feed-link"><a href="https://pub.towardsai.net/pandas-cut-vs-qcut-explained-clearly-finally-905847d473bd?source=rss-39db050c2ac2------2">Continue reading on Towards AI »</a></p></div>]]></description>
            <link>https://pub.towardsai.net/pandas-cut-vs-qcut-explained-clearly-finally-905847d473bd?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/905847d473bd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 18:01:59 GMT</pubDate>
            <atom:updated>2023-11-30T18:01:59.683Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Why You (Almost) Can’t Calculate Pi to a Billion Digits in Python at Home]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/data-science/why-you-almost-cant-calculate-pi-to-a-billion-digits-in-python-at-home-4262a4de9f80?source=rss-39db050c2ac2------2"><img src="https://cdn-images-1.medium.com/max/600/1*Jl8A4AJLlLEZt9AYY1iZ5Q.png" width="600"></a></p><p class="medium-feed-snippet">It is much harder than you think</p><p class="medium-feed-link"><a href="https://medium.com/data-science/why-you-almost-cant-calculate-pi-to-a-billion-digits-in-python-at-home-4262a4de9f80?source=rss-39db050c2ac2------2">Continue reading on TDS Archive »</a></p></div>]]></description>
            <link>https://medium.com/data-science/why-you-almost-cant-calculate-pi-to-a-billion-digits-in-python-at-home-4262a4de9f80?source=rss-39db050c2ac2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4262a4de9f80</guid>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Bex T.]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 15:21:12 GMT</pubDate>
            <atom:updated>2023-10-09T15:23:27.767Z</atom:updated>
        </item>
    </channel>
</rss>