Certainly! Here's an example Scrapy spider that will yield all URLs starting with a specified domain from the given URL recursively using CrawlSpider and LinkExtractor:
import scrapy
from scrapy.http import LinkRequest
from scrapy.linkextractors import LinkExtractor
class RecursiveLinkExtractor(LinkExtractor):
def __init__(self, url_prefix):
self.url_prefix = url_prefix
def parse(self, response):
for link in response.css('a::attr(href)${self.url_prefix}::attr(href)'):
yield LinkRequest(link, self.url_prefix + link)
class RecursiveCrawlSpider(scrapy.Spider):
name = "RecursiveLinkCrawler"
start_urls = ["http://example.com"]
def __init__(self, domain):
self.domain = domain
def parse(self, response):
for link in RecursiveLinkExtractor(self.domain).parse(response):
yieldyield response.url
In this example, we define a RecursiveLinkExtractor class that takes a URL prefix as an argument and returns all URLs starting with the given domain. We then create a RecursiveCrawlSpider and set its start_urls to the domains we want to crawl recursively.
The RecursiveLinkExtractor class uses CSS selector to find all anchor tags with a href attribute that starts with the given domain. We then use the yield statement to yield all the URLs from the given link to the RecursiveLinkCrawler spider.
To use this spider, you can create a new scrapy project and then create a new spider like this:
import scrapy
class MySpider(scrapy.Spider):
name = "my_spider"
start_urls = ["http://example.com"]
def __init__(self, domain):
self.domain = domain
def parse(self, response):
for link in RecursiveLinkExtractor(self.domain).parse(response):
yieldyield response.url
# Start the crawl
scrapy crawl my_spider
This will start the crawl at the http://example.com domain and recursively crawl all the links on the website. You can modify the start_urls variable to start the crawl at a different domain.