Creating a web crawler to collect online coupons involves several steps, from targeting the right websites to storing the collected coupons. Below is a basic outline of how you might approach this task using Python, along with a simplified example code. This example will focus on crawling coupon titles and codes from a hypothetical target website. Please note:
Legality and Ethics: Ensure you have the right to crawl a website. Check the website's robots.txt file (e.g., www.example.com/robots.txt) and terms of service. Respect websites that disallow crawling. For example, you can crawl coupons from retailmenot.com, coupons.com, or couponcabin.com, but always ensure compliance with their policies.
Dynamic Content: This example uses static HTML content. For dynamically loaded content (e.g., via JavaScript), consider using Selenium or Scrapy with Splash.
Rate Limiting: Don't overload the target server with too many requests per second to avoid being blocked.
Handling CAPTCHAs: Some websites may block your crawler if they detect unusual traffic. Use services like 2captcha or deathbycaptcha to solve CAPTCHAs programmatically.
Requirements
Python 3.x
requests for HTTP requests
beautifulsoup4 for HTML parsing
scrapy (optional, for more advanced crawling needs)
selenium or scrapy-splash for handling dynamic content
backoff for handling rate limiting and retries
Example Using requests and beautifulsoup4
Step 1: Install Required Libraries
bash
pip install requests beautifulsoup4 backoff
Step 2: Python Script for Crawling
python
import requests
from bs4 import BeautifulSoup
import csv
from backoff import on_exception, expo
from ratelimit import limits, sleep_time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
# Target Website URL
url = "http://example.com/coupons" # REPLACE WITH THE TARGET WEBSITE, e.g., retailmenot.com
# Set up Selenium for dynamic content
def setup_selenium():
"""Initialize Selenium WebDriver for handling dynamic content."""
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
return driver
# Send HTTP Request with retries
@on_exception(expo, requests.exceptions.RequestException, max_tries=5)
@limits(calls=5, period=60) # 5 calls per 60 seconds
def fetch_page(url):
"""Fetch the webpage content with rate limiting and retries."""
try:
response = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})
response.raise_for_status() # Raise an exception for HTTP errors
return response.text
except requests.exceptions.RequestException as err:
print("Error occurred: ", err)
raise
# Parse HTML Content
def parse_coupons(html):
"""Parse the HTML to extract coupon titles and codes."""
soup = BeautifulSoup(html, 'html.parser')
coupons = soup.find_all('div', class_='coupon')
# Extract and return coupon data
coupon_data = []
for coupon in coupons:
title = coupon.find('h3').text.strip() if coupon.find('h3') else "No Title"
code = coupon.find('p', class_='code').text.strip() if coupon.find('p', class_='code') else "No Code"
coupon_data.append({'title': title, 'code': code})
return coupon_data
# Handle pagination
def crawl_pagination(base_url, pages=5):
"""Crawl multiple pages of coupons."""
all_coupons = []
for page in range(1, pages + 1):
page_url = f"{base_url}?page={page}"
html = fetch_page(page_url)
coupons = parse_coupons(html)
all_coupons.extend(coupons)
return all_coupons
# Store Coupons in a CSV File
def save_coupons(coupons, filename='coupons.csv'):
"""Save the crawled coupons to a CSV file."""
with open(filename, 'w', newline='') as csvfile:
fieldnames = ['title', 'code']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for coupon in coupons:
writer.writerow(coupon)
# Main execution
if __name__ == "__main__":
# Crawl coupons with pagination
base_url = url
coupons = crawl_pagination(base_url, pages=3) # Adjust the number of pages
# Save coupons to CSV
save_coupons(coupons)
print("Coupons have been crawled and saved to coupons.csv")
Optional: Using Scrapy for More Advanced Crawling
For more complex scenarios (handling different types of pages, following links, handling forms, etc.), consider using Scrapy. Here’s a brief setup:
Step 1: Install Scrapy
bash
pip install scrapy
Step 2: Create a New Scrapy Project
bash
scrapy startproject coupon_crawler
cd coupon_crawler
Step 3: Generate a Spider
bash
scrapy genspider example example.com
Step 4: Edit the Spider (example.py in coupon_crawler/spiders/)
python
import scrapy
from scrapy_splash import SplashRequest
class ExampleSpider(scrapy.Spider):
name = "example"
start_urls = [
'http://example.com/coupons',
]
# Use Splash for dynamic content
def start_requests(self):
for url in self.start_urls:
yield SplashRequest(url, self.parse, args={'wait': 0.5})
def parse(self, response):
coupons = response.css('div.coupon')
for coupon in coupons:
yield {
'title': coupon.css('h3::text').get().strip(),
'code': coupon.css('p.code::text').get().strip(),
}
# Follow pagination
next_page = response.css('li.next a::attr(href)').get()
if next_page is not None:
next_page = response.urljoin(next_page)
yield SplashRequest(next_page, self.parse, args={'wait': 0.5})
This will save the crawled coupons in a coupons.json file.
Remember, the effectiveness and legality of your crawler heavily depend on the specifics of your target and how you've implemented the crawler. Always ensure you're complying with the target website's policies.