How to extract HTML data using Scrapy?

Abstract: Extract structured data from HTML pages using Scrapy by defining items, creating spiders, and applying CSS or XPath selectors.

Created: 2026-09-30 by
To extract HTML data using Scrapy, you must define an Item class to structure your fields and create a Spider subclass that parses responses. By implementing the parse method with CSS or XPath selectors, you can target specific elements, yield the extracted data as dictionaries, and handle pagination for comprehensive data collection across multiple pages.

Setting Up the Project Structure

Before writing any extraction logic, you need a properly initialized Scrapy project. This framework organizes your spiders, items, and pipelines into a coherent structure. Start by creating a new project using the command line interface. Run scrapy startproject myproject in your terminal. This command generates a directory containing essential configuration files like settings.py and items.py. The items.py file is where you define the schema of the data you intend to scrape. Using a structured item ensures that your data remains consistent and easy to process later. You should import the necessary classes from scrapy and declare each field you plan to extract. For example, if you are scraping product titles and prices, you would define them as string fields within the Item class. This step is critical because it serves as the contract between your spider and the rest of the pipeline. Without defined items, your code may become messy and difficult to maintain as the complexity of your scraping task increases.

Creating the Spider Class

The core of any Scrapy scraping operation is the Spider class. A spider defines how to follow links and extract data from individual pages. You need to create a new Python file inside the spiders directory of your project. Import Spider from scrapy and define a subclass. You must set three attributes: name, which identifies the spider; allowed_domains, which restricts requests to specific domains for safety; and start_urls, which provides the initial URLs to crawl. When Scrapy runs this spider, it fetches the start_urls and passes the HTTP response to the parse method. This method is responsible for processing the HTML content. It receives a Response object that contains the body of the page, headers, and other metadata. Your job in this method is to identify the relevant parts of the HTML and convert them into structured data. Remember that Scrapy handles the asynchronous nature of HTTP requests automatically, allowing you to focus on the parsing logic rather than network management.

Using Selectors for Extraction

Extracting data requires selecting specific nodes from the HTML DOM tree. Scrapy provides two primary methods for this: CSS selectors and XPath expressions. CSS selectors are generally easier to read and write for simple tasks. You can use the .css() method on the response object to find elements. For instance, response.css('h1.title::text') selects all text within h1 tags with the class title. The double colon ::text is crucial because it extracts the text content rather than the tag itself. If you need more complex logic, such as conditional selection or navigating up the tree, XPath is often more powerful. Use the .xpath() method similarly. Both methods return a list of selector objects. To get the actual value, call the .get() method for a single result or .getall() for multiple results. Always test your selectors in the browser console or using the scrapy shell command before integrating them into your spider. This practice saves time debugging broken paths. For dynamic content that relies heavily on JavaScript, standard HTML extraction might fail, requiring alternative approaches like rendering engines, but for static HTML, these selectors are highly effective.

Pagination and Data Yielding

Real-world websites rarely present all desired data on a single page. You must implement pagination to traverse through multiple pages. After extracting data from the current page, look for a link to the next page. This link is usually found in a footer or header element. Use your selector to find this link and construct its absolute URL. If the link exists, yield a new Request object pointing to that URL. In Scrapy, you can pass a callback function to the request, telling Scrapy to use a different parser for subsequent pages if needed. Often, however, the same parse method handles both the first and subsequent pages. Inside the loop, after extracting the data for the current item, use the yield keyword to return the dictionary containing your scraped fields. This sends the data to the Scrapy engine, which then processes it through your configured pipelines. Ensure that your pagination logic has a stopping condition to prevent infinite loops. Check if the next page link is null or if you have reached a maximum depth. Properly handling pagination ensures you capture the complete dataset without wasting resources on redundant or non-existent pages.

Running and Saving the Output

Once your spider is complete, you can run it using the Scrapy CLI. Execute scrapy crawl myspider in the root directory of your project. Scrapy will display logs showing the progress of requests and responses. To save your extracted data, use the -o flag followed by the filename and format. For example, scrapy crawl myspider -o output.json saves the data as a JSON file. Other supported formats include CSV and XML. These files contain all the yielded items in a structured manner. You can also configure pipelines in settings.py to perform additional processing, such as cleaning data or storing it in a database. The built-in feed exports are sufficient for most initial testing and small-scale projects. As your project grows, you might want to implement custom pipelines for more robust data handling. Always review the output file to ensure that the selectors are capturing the correct information. If fields are empty or malformed, revisit your CSS or XPath expressions. This iterative process of running, checking, and refining is central to successful web scraping with Scrapy.

Frequently Asked Questions

How do I handle dynamic JavaScript content?

Scrapy does not execute JavaScript by default, so it cannot see content loaded via AJAX. You can integrate Splash or Selenium to render the page before parsing. Alternatively, inspect the network traffic to find the underlying API endpoints that provide the raw JSON data directly.

What is the difference between .get() and .getall()?

Use .get() when you expect a single element and want a string result. Use .getall() when targeting multiple elements, as it returns a list of strings. Choosing the wrong method can lead to type errors when processing the data later.

How can I avoid getting banned while scraping?

Implement delays between requests using the DOWNLOAD_DELAY setting in your Scrapy settings. Rotate user agents and respect the robots.txt file of the target website. Consider using proxy rotation services if you need to make a high volume of requests.

Can I reuse the same parse method for all pages?

Yes, if the HTML structure is identical across all pages, you can use a single parse method. Just ensure that your pagination logic correctly yields requests for the next page within that same method. This simplifies maintenance and reduces code duplication.

Why are my selectors returning empty lists?

This usually happens if the HTML structure changes or if the elements are loaded dynamically. Verify your selectors using the Scrapy shell or browser developer tools. Ensure that you are targeting the correct scope, especially when nested within other containers.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More