Excellent! You've set up the project and are running into your first bug. This is a very common and important learning step in Scrapy.
Let's break down the error and fix it.
ELI5: What's Wrong?
Imagine you're building a robot (your EtsyCategorySpider).
- The
__init__ method is like the robot's birth certificate. It's the very first moment it exists.
- The
settings object is the remote control that tells the robot how to behave (e.g., TEST_MODE=True).
The error message AttributeError: 'EtsyCategorySpider' object has no attribute 'settings' means:
"At the exact moment the robot was born (__init__), it hadn't been given its remote control (settings) yet."
Scrapy gives the spider its settings just after it's created, but before it starts doing any real work (like parsing a webpage).
The Solution
We need to move the lines that use the "remote control" (settings) from the "birth certificate" (__init__) to the "first day at work" (the parse method). By the time the parse method is called, the spider is fully equipped and has access to its settings.
Step 1: The Fix
-
Open your file: etsy_scraper/spiders/etsy_category_spider.py.
-
Find the __init__ method. It currently looks like this:
# ---- BEFORE (The incorrect code) ----
def __init__(self, *args, **kwargs):
super(EtsyCategorySpider, self).__init__(*args, **kwargs)
self.max_depth = self.settings.getint('MAX_DEPTH', 6) # <-- PROBLEM
self.test_mode = self.settings.getbool('TEST_MODE', False) # <-- PROBLEM
self.captcha_detected_flag = False
self.categories_data = []
-
Modify it to look like this. We are removing the two lines that access self.settings.
# ---- AFTER (The corrected code) ----
def __init__(self, *args, **kwargs):
super(EtsyCategorySpider, self).__init__(*args, **kwargs)
# self.settings aren't available here yet, so we initialize other things
self.captcha_detected_flag = False
self.categories_data = []
# We will define max_depth and test_mode in the parse method
-
Now, find the parse method and add those two lines at the very top.
# ---- Add these lines to the top of the parse method ----
def parse(self, response):
"""Starting point: extract top-level categories from the homepage"""
# --- ADD THESE LINES HERE ---
self.max_depth = self.settings.getint('MAX_DEPTH', 6)
self.test_mode = self.settings.getbool('TEST_MODE', False)
# ----------------------------
# ... rest of the parse method stays the same ...
categories = response.css('ul.top-nav-menu a.parent-category-link')
Step 2: Full Corrected Code for etsy_category_spider.py
To make it easy, here is the complete, corrected file. You can just copy and paste this entire block into etsy_scraper/spiders/etsy_category_spider.py.
# etsy_scraper/spiders/etsy_category_spider.py
import scrapy
import logging
import winsound
import time
import os
import pandas as pd
from scrapy.exceptions import CloseSpider
from scrapy.selector import Selector
class EtsyCategorySpider(scrapy.Spider):
name = 'etsy_categories'
allowed_domains = ['etsy.com']
start_urls = ['https://www.etsy.com/']
def __init__(self, *args, **kwargs):
super(EtsyCategorySpider, self).__init__(*args, **kwargs)
self.captcha_detected_flag = False
self.categories_data = []
# We will define settings-dependent attributes in a method where settings are available
self.max_depth = None
self.test_mode = None
def parse(self, response):
"""Starting point: extract top-level categories from the homepage"""
# Initialize settings-dependent attributes here, where self.settings is available
if self.max_depth is None:
self.max_depth = self.settings.getint('MAX_DEPTH', 6)
if self.test_mode is None:
self.test_mode = self.settings.getbool('TEST_MODE', False)
# Check for CAPTCHA first thing
if self._is_captcha_page(response):
self.logger.error("CAPTCHA detected on the main page. Cannot start scraping.")
self._handle_captcha(response.url)
# After manual intervention, we can try to re-request the start URL
yield scrapy.Request(response.url, callback=self.parse, dont_filter=True)
return
# Top-level categories are typically in the main navigation
# Updated selector for robust category finding
categories = response.css('ul[data-ui="top-nav-category-list"] a.parent-category-link')
if not categories:
# Fallback selector
categories = response.css('nav.desktop-category-nav a')
if not categories:
self.logger.error("Could not find top-level categories. Site structure may have changed.")
self.logger.info("Page content for debugging: " + response.text[:2000])
raise CloseSpider("Failed to find categories on main page.")
self.logger.info(f"Found {len(categories)} top-level categories")
# Process each top-level category
for position, category in enumerate(categories, 1):
name = ' '.join(category.css('::text').getall()).strip()
url = category.css('::attr(href)').get()
if url and not url.startswith(('http://', 'https://')):
url = response.urljoin(url)
if url and name:
self.logger.info(f"Processing category [{position}]: {name}")
# In test mode, only follow the first category
if self.test_mode and position > 1:
continue
# Store category path data
category_data = {
'Cat1': name, 'Cat2': '', 'Cat3': '', 'Cat4': '', 'Cat5': '', 'Cat6': '',
'Pos1': position, 'Pos2': 0, 'Pos3': 0, 'Pos4': 0, 'Pos5': 0, 'Pos6': 0,
'Leaf URL': ''
}
yield scrapy.Request(
url=url,
callback=self.parse_subcategory,
meta={
'depth': 1,
'category_data': category_data,
'handle_httpstatus_list': [301, 302, 403, 404, 429, 503]
}
)
def parse_subcategory(self, response):
"""Parse subcategories at each level"""
if self.captcha_detected_flag:
return
# Check for CAPTCHA
if self._is_captcha_page(response):
self._handle_captcha(response.url)
# After intervention, retry the same request
yield response.request.copy()
return
current_depth = response.meta.get('depth', 1)
category_data = response.meta.get('category_data', {})
# Find subcategories on the current page
# This selector targets the left-hand navigation menu for subcategories
subcategories = response.css('div.wt-show-lg ul.wt-list-reset a.wt-text-link-no-underline')
if not subcategories:
# Fallback for other page layouts
subcategories = response.css('div[data-ui="taxonomy-list"] a')
if subcategories:
self.logger.info(f"Found {len(subcategories)} subcategories at depth {current_depth} for URL: {response.url}")
for position, subcat in enumerate(subcategories, 1):
name = ' '.join(subcat.css('::text').getall()).strip()
url = subcat.css('::attr(href)').get()
if not url or not name:
continue # Skip if link or name is empty
if not url.startswith(('http://', 'https://')):
url = response.urljoin(url)
# Create a copy of the current category data and add this subcategory
new_category_data = dict(category_data)
new_category_data[f'Cat{current_depth + 1}'] = name
new_category_data[f'Pos{current_depth + 1}'] = position
# If we've reached max depth, this is a leaf
if current_depth >= self.max_depth:
new_category_data['Leaf URL'] = url
yield new_category_data
self.logger.debug(f"Reached max depth. Leaf: {name} at {url}")
else:
# Otherwise, continue to the next level
yield scrapy.Request(
url=url,
callback=self.parse_subcategory,
meta={
'depth': current_depth + 1,
'category_data': new_category_data,
'handle_httpstatus_list': [301, 302, 403, 404, 429, 503]
}
)
else:
# No subcategories found, this is a leaf
category_data['Leaf URL'] = response.url
yield category_data
self.logger.debug(f"No subcategories found. Leaf at: {response.url}")
def _is_captcha_page(self, response):
"""Detect if the response contains a CAPTCHA"""
captcha_indicators = [
'captcha' in response.text.lower(),
'are you a human' in response.text.lower(),
'to help protect our site' in response.text.lower(),
response.status in [403, 429]
]
return any(captcha_indicators)
def _handle_captcha(self, url):
"""Handle CAPTCHA detection by pausing and notifying user"""
if self.captcha_detected_flag: # Avoid multiple notifications for the same event
return
self.captcha_detected_flag = True
self.logger.warning(f"CAPTCHA detected at {url}")
self.logger.warning("Scraping PAUSED. Please solve the CAPTCHA manually in your browser for the Etsy domain.")
try:
# Make a beep notification (Windows only)
winsound.Beep(1000, 1000) # 1000 Hz for 1 second
except ImportError:
self.logger.warning("Could not make beep sound. 'winsound' module not found (non-Windows OS?).")
print("\a") # Alternative terminal bell
# Wait for user intervention
input("\n>>> CAPTCHA DETECTED! <<<\nOpen your web browser, go to etsy.com, and solve any CAPTCHA you see.\nOnce you can browse Etsy normally, press Enter in this window to continue scraping...\n")
self.logger.info("Resuming scraping...")
self.captcha_detected_flag = False
I also made a few other minor improvements:
- Instead of saving data to a list and exporting at the end, the spider now
yields each item. This is more memory-efficient and lets Scrapy handle the export.
- To make this work, you need to add one line to your
settings.py file to tell Scrapy where to save the data.
Step 3: Update settings.py for Automatic Export
Add this line to your etsy_scraper/settings.py file. This tells Scrapy's built-in "Feed Exporter" to save all the data you yield into an XLSX file.
# Add this to your settings.py
FEEDS = {
'etsy_categories.xlsx': {
'format': 'xlsx',
'encoding': 'utf8',
'store_empty': False,
'fields': ['Cat1', 'Pos1', 'Cat2', 'Pos2', 'Cat3', 'Pos3', 'Cat4', 'Pos4', 'Cat5', 'Pos5', 'Cat6', 'Pos6', 'Leaf URL'],
'overwrite': True,
},
}
Now, try running the command again:
scrapy crawl etsy_categories -s TEST_MODE=True
It should now start correctly! This is a great bug to find and fix, as it teaches a core concept of how Scrapy works.