diff --git a/README.md b/README.md deleted file mode 100644 index 3ae235b..0000000 --- a/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Data Engineering Internship Assignment - -Welcome to the Data Engineering Internship Assignment! This task is designed to evaluate your problem-solving skills, understanding of data pipelines, and ability to work with web crawling and data extraction. Please read the instructions carefully and submit your solution as per the guidelines provided. - -## Problem Statement - -You are tasked with building a basic web crawling pipeline to extract and process data from a target website. The goal is to: - -1. **Crawl** a given webpage to extract specific information. -2. **Clean and process** the extracted data. -3. **Store** the processed data into a MongoDB database. - -### Target Website - -You will be working with the Books to Scrape website (http://books.toscrape.com/) or any other publicly accessible e-commerce website containing product information. Ensure that your crawler abides by the website's `robots.txt` policy. - -### Tasks - -#### Step 1: Web Crawling - -1. Use the `Scrapy` framework to: - - Fetch the HTML content of the target webpage. - - Extract product details such as: - - `Product Name` - - `Price` - - `Rating` - - `Availability Status` - -#### Step 2: Data Transformation - -1. Clean the extracted data (e.g., remove extra whitespace, convert prices to float, handle missing ratings). -2. Standardize the data (e.g., convert availability status to `In Stock` or `Out of Stock`). - -#### Step 3: Data Storage - -1. Store the processed data into a MongoDB database. -2. Use a collection named `products` with the following schema: - - `product_name` (string) - - `price` (float) - - `rating` (float) - - `availability` (string) - -#### Step 4: Documentation - -Prepare a `README.md` file that includes: -1. An overview of your solution. -2. Steps to set up and run your crawler. -3. Dependencies and setup instructions. - -#### Step 5: Git Guidelines - -1. Use meaningful commit messages. -2. Follow a proper branch naming convention (e.g., `feature/`). -3. Ensure your code is clean, modular, and well-commented. - -## Submission Guidelines - -1. Fork this repository. -2. Create a new branch named `submission/`. -3. Commit your code and push it to your forked repository. -4. Create a Pull Request (PR) to the `main` branch of this repository. -5. Include your `README.md` and ensure your code is well-documented. - -## Evaluation Criteria - -1. **Correctness**: Does your solution meet the requirements? -2. **Code Quality**: Is your code clean, modular, and well-documented? -3. **Efficiency**: Are the crawling and transformations optimized? -4. **Git Practices**: Are proper git guidelines followed? - ---- - -Good luck! We look forward to reviewing your submission. diff --git a/books_scraper/__init__.py b/books_scraper/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/books_scraper/__pycache__/__init__.cpython-39.pyc b/books_scraper/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000..129e298 Binary files /dev/null and b/books_scraper/__pycache__/__init__.cpython-39.pyc differ diff --git a/books_scraper/__pycache__/pipelines.cpython-39.pyc b/books_scraper/__pycache__/pipelines.cpython-39.pyc new file mode 100644 index 0000000..352f814 Binary files /dev/null and b/books_scraper/__pycache__/pipelines.cpython-39.pyc differ diff --git a/books_scraper/__pycache__/settings.cpython-39.pyc b/books_scraper/__pycache__/settings.cpython-39.pyc new file mode 100644 index 0000000..7bc07f0 Binary files /dev/null and b/books_scraper/__pycache__/settings.cpython-39.pyc differ diff --git a/books_scraper/items.py b/books_scraper/items.py new file mode 100644 index 0000000..42c4bad --- /dev/null +++ b/books_scraper/items.py @@ -0,0 +1,12 @@ +# Define here the models for your scraped items +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/items.html + +import scrapy + + +class BooksScraperItem(scrapy.Item): + # define the fields for your item here like: + # name = scrapy.Field() + pass diff --git a/books_scraper/middlewares.py b/books_scraper/middlewares.py new file mode 100644 index 0000000..b11eee6 --- /dev/null +++ b/books_scraper/middlewares.py @@ -0,0 +1,103 @@ +# Define here the models for your spider middleware +# +# See documentation in: +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + +# useful for handling different item types with a single interface +from itemadapter import is_item, ItemAdapter + + +class BooksScraperSpiderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(self, response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(self, response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, or item objects. + for i in result: + yield i + + def process_spider_exception(self, response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Request or item objects. + pass + + def process_start_requests(self, start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) + + +class BooksScraperDownloaderMiddleware: + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the downloader middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_request(self, request, spider): + # Called for each request that goes through the downloader + # middleware. + + # Must either: + # - return None: continue processing this request + # - or return a Response object + # - or return a Request object + # - or raise IgnoreRequest: process_exception() methods of + # installed downloader middleware will be called + return None + + def process_response(self, request, response, spider): + # Called with the response returned from the downloader. + + # Must either; + # - return a Response object + # - return a Request object + # - or raise IgnoreRequest + return response + + def process_exception(self, request, exception, spider): + # Called when a download handler or a process_request() + # (from other downloader middleware) raises an exception. + + # Must either: + # - return None: continue processing this exception + # - return a Response object: stops process_exception() chain + # - return a Request object: stops process_exception() chain + pass + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git a/books_scraper/pipelines.py b/books_scraper/pipelines.py new file mode 100644 index 0000000..9bdde01 --- /dev/null +++ b/books_scraper/pipelines.py @@ -0,0 +1,39 @@ +import pymongo + +class BooksScraperPipeline: + def __init__(self): + # MongoDB setup + self.client = pymongo.MongoClient("mongodb://localhost:27017/") + self.db = self.client["books_database"] + self.collection = self.db["products"] + + def process_item(self, item, spider): + # Clean and process the product_name + item['product_name'] = item['product_name'].strip() if item['product_name'] else "Unknown Product" + + # Clean and convert the price to float + if item['price']: + item['price'] = float(item['price'].replace('£', '').strip()) + else: + item['price'] = 0.0 # Default to 0.0 if the price is missing + + # Convert rating to float + rating_map = {'One': 1.0, 'Two': 2.0, 'Three': 3.0, 'Four': 4.0, 'Five': 5.0} + item['rating'] = rating_map.get(item['rating'], 0.0) # Default to 0.0 if rating is missing + + # Clean and standardize availability + raw_availability = item['availability'].lower() if item['availability'] else '' + item['availability'] = 'In Stock' if 'in stock' in raw_availability else 'Out of Stock' + + # Insert the cleaned and processed item into MongoDB + self.collection.insert_one({ + "product_name": item['product_name'], + "price": item['price'], + "rating": item['rating'], + "availability": item['availability'] + }) + return item + + def close_spider(self, spider): + # Close the MongoDB connection + self.client.close() diff --git a/books_scraper/readme.md b/books_scraper/readme.md new file mode 100644 index 0000000..617e83f --- /dev/null +++ b/books_scraper/readme.md @@ -0,0 +1,34 @@ +# Books Web Scraper + +This project is a web scraper built using the Scrapy framework. It crawls the [Books to Scrape](http://books.toscrape.com/) website to extract product details such as name, price, rating, and availability. The extracted and cleaned data is stored in a MongoDB database. + +--- + +## Overview + +The scraper performs the following tasks: +1. Crawls the website to extract: + - Product Name + - Price + - Rating + - Availability +2. Cleans and processes the extracted data: + - Converts price to float + - Maps ratings to numerical values + - Standardizes availability to "In Stock" or "Out of Stock" +3. Stores the processed data into a MongoDB database with the schema: + - `product_name` (string) + - `price` (float) + - `rating` (float) + - `availability` (string) + +--- + +## Setup and Running the Scraper + +### Prerequisites +- Python 3.7 or above +- MongoDB installed and running locally +- pip (Python package manager) + + diff --git a/books_scraper/settings.py b/books_scraper/settings.py new file mode 100644 index 0000000..d2e5c6a --- /dev/null +++ b/books_scraper/settings.py @@ -0,0 +1,91 @@ +# Scrapy settings for books_scraper project +# +# For simplicity, this file contains only settings considered important or +# commonly used. You can find more settings consulting the documentation: +# +# https://docs.scrapy.org/en/latest/topics/settings.html +# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +# https://docs.scrapy.org/en/latest/topics/spider-middleware.html + +BOT_NAME = 'books_scraper' + +SPIDER_MODULES = ['books_scraper.spiders'] +NEWSPIDER_MODULE = 'books_scraper.spiders' + + +# Crawl responsibly by identifying yourself (and your website) on the user-agent +#USER_AGENT = 'books_scraper (+http://www.yourdomain.com)' + +# Obey robots.txt rules +ROBOTSTXT_OBEY = True + +# Configure maximum concurrent requests performed by Scrapy (default: 16) +#CONCURRENT_REQUESTS = 32 + +# Configure a delay for requests for the same website (default: 0) +# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay +# See also autothrottle settings and docs +#DOWNLOAD_DELAY = 3 +# The download delay setting will honor only one of: +#CONCURRENT_REQUESTS_PER_DOMAIN = 16 +#CONCURRENT_REQUESTS_PER_IP = 16 + +# Disable cookies (enabled by default) +#COOKIES_ENABLED = False + +# Disable Telnet Console (enabled by default) +#TELNETCONSOLE_ENABLED = False + +# Override the default request headers: +#DEFAULT_REQUEST_HEADERS = { +# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', +# 'Accept-Language': 'en', +#} + +# Enable or disable spider middlewares +# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html +#SPIDER_MIDDLEWARES = { +# 'books_scraper.middlewares.BooksScraperSpiderMiddleware': 543, +#} + +# Enable or disable downloader middlewares +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html +#DOWNLOADER_MIDDLEWARES = { +# 'books_scraper.middlewares.BooksScraperDownloaderMiddleware': 543, +#} + +# Enable or disable extensions +# See https://docs.scrapy.org/en/latest/topics/extensions.html +#EXTENSIONS = { +# 'scrapy.extensions.telnet.TelnetConsole': None, +#} + +# Configure item pipelines +# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html +#ITEM_PIPELINES = { +# 'books_scraper.pipelines.BooksScraperPipeline': 300, +#} + +# Enable and configure the AutoThrottle extension (disabled by default) +# See https://docs.scrapy.org/en/latest/topics/autothrottle.html +#AUTOTHROTTLE_ENABLED = True +# The initial download delay +#AUTOTHROTTLE_START_DELAY = 5 +# The maximum download delay to be set in case of high latencies +#AUTOTHROTTLE_MAX_DELAY = 60 +# The average number of requests Scrapy should be sending in parallel to +# each remote server +#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 +# Enable showing throttling stats for every response received: +#AUTOTHROTTLE_DEBUG = False + +# Enable and configure HTTP caching (disabled by default) +# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings +#HTTPCACHE_ENABLED = True +#HTTPCACHE_EXPIRATION_SECS = 0 +#HTTPCACHE_DIR = 'httpcache' +#HTTPCACHE_IGNORE_HTTP_CODES = [] +#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' +ITEM_PIPELINES = { + 'books_scraper.pipelines.BooksScraperPipeline': 300, +} diff --git a/books_scraper/spiders/__init__.py b/books_scraper/spiders/__init__.py new file mode 100644 index 0000000..ebd689a --- /dev/null +++ b/books_scraper/spiders/__init__.py @@ -0,0 +1,4 @@ +# This package will contain the spiders of your Scrapy project +# +# Please refer to the documentation for information on how to create and manage +# your spiders. diff --git a/books_scraper/spiders/__pycache__/__init__.cpython-39.pyc b/books_scraper/spiders/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000..6b97c34 Binary files /dev/null and b/books_scraper/spiders/__pycache__/__init__.cpython-39.pyc differ diff --git a/books_scraper/spiders/__pycache__/books_spider.cpython-39.pyc b/books_scraper/spiders/__pycache__/books_spider.cpython-39.pyc new file mode 100644 index 0000000..5b4a84b Binary files /dev/null and b/books_scraper/spiders/__pycache__/books_spider.cpython-39.pyc differ diff --git a/books_scraper/spiders/books_spider.py b/books_scraper/spiders/books_spider.py new file mode 100644 index 0000000..c62d79e --- /dev/null +++ b/books_scraper/spiders/books_spider.py @@ -0,0 +1,28 @@ +import scrapy + +class BooksSpider(scrapy.Spider): + name = "books_spider" + start_urls = ['http://books.toscrape.com/'] + + def parse(self, response): + for book in response.css('article.product_pod'): + # Extract data + product_name = book.css('h3 a::attr(title)').get() + price = book.css('p.price_color::text').get() + rating = book.css('p::attr(class)').re_first('star-rating (\w+)') + availability_raw = book.css('p.instock.availability::text').getall() + + # Clean and process availability + availability = ''.join(availability_raw).strip() # Combine all text and strip spaces + + yield { + 'product_name': product_name, + 'price': price, + 'rating': rating, + 'availability': availability, + } + + # Handle pagination + next_page = response.css('li.next a::attr(href)').get() + if next_page: + yield response.follow(next_page, self.parse) diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..3015bbb --- /dev/null +++ b/readme.md @@ -0,0 +1,88 @@ + +# Books Web Scraper + +This project is a web scraper built using the Scrapy framework. It crawls the [Books to Scrape](http://books.toscrape.com/) website to extract product details such as name, price, rating, and availability. The extracted and cleaned data is stored in a MongoDB database. + +--- + +## Overview + +The scraper performs the following tasks: +1. Crawls the website to extract: + - Product Name + - Price + - Rating + - Availability +2. Cleans and processes the extracted data: + - Converts price to float + - Maps ratings to numerical values + - Standardizes availability to "In Stock" or "Out of Stock" +3. Stores the processed data into a MongoDB database with the schema: + - `product_name` (string) + - `price` (float) + - `rating` (float) + - `availability` (string) + +--- + +## Setup and Running the Scraper + +### Prerequisites +- Python 3.7 or above +- MongoDB installed and running locally +- pip (Python package manager) +- **Scrapy**: For web scraping. +- **pymongo**: To interact with MongoDB. +- **Rust Compiler**: Required for building certain Python packages (e.g., cryptography). + +--- + +### Installation + +1. Clone the repository: + ```bash + git clone + cd + ``` + +2. Create and activate a virtual environment: + ```bash + python -m venv venv + venv\Scripts\activate + ``` + +3. Install dependencies: + ```bash + pip install scrapy pymongo + ``` + +4. Ensure MongoDB is running locally + + + + + +### Running the Crawler + +1. Navigate to the project directory: + ```bash + cd bookscraper + ``` + +2. Run the Scrapy spider: + ```bash + scrapy crawl books_spider + ``` + +3. Check MongoDB Compass to verify the scraped data in the `books_database` under the `products` collection. + +--- + +## Dependencies +- **Scrapy**: For web crawling and data extraction. +- **pymongo**: To interact with MongoDB. +- **Rust**: Required for certain Python dependencies (e.g., cryptography). + + + +