Scrapy是一个强大的Python爬虫框架,你可以通过修改其配置、编写自定义的爬虫类、中间件等来定制你的爬虫。以下是一些常见的修改方法:
Scrapy的配置存储在settings.py
文件中。你可以直接修改这个文件来改变爬虫的行为。
# settings.py
# 设置下载延迟时间
DOWNLOAD_DELAY = 3
# 设置User-Agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
# 设置是否使用代理
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.ProxyMiddleware': 100,
}
你可以创建一个继承自scrapy.Spider
的类来定义你的爬虫。
# myspider.py
import scrapy
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://example.com']
def parse(self, response):
# 解析逻辑
title = response.css('title::text').get()
yield {'title': title}
Scrapy支持中间件,可以在请求和响应之间插入自定义的逻辑。
# myproject/middlewares.py
import scrapy
class ProxyMiddleware(object):
def process_request(self, request, spider):
request.meta['proxy'] = 'http://your_proxy:port'
然后在settings.py
中启用这个中间件:
# settings.py
DOWNLOADER_MIDDLEWARES = {
'myproject.middlewares.ProxyMiddleware': 100,
}
Scrapy使用Item
和Field
来定义爬取的数据结构。
# myproject/items.py
import scrapy
class MyItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
然后在爬虫中使用这个Item:
# myspider.py
import scrapy
from myproject.items import MyItem
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://example.com']
def parse(self, response):
item = MyItem()
item['title'] = response.css('title::text').get()
item['link'] = response.url
yield item
Scrapy提供了信号机制,可以在爬虫的生命周期中插入自定义逻辑。
# myproject/signals.py
from scrapy import signals
class MySpider(scrapy.Spider):
name = 'myspider'
start_urls = ['http://example.com']
@classmethod
def from_crawler(cls, crawler, *args, **kwargs):
spider = super(MySpider, cls).from_crawler(crawler, *args, **kwargs)
crawler.signals.connect(spider.spider_opened, signal=signals.spider_opened)
return spider
def spider_opened(self, spider):
spider.logger.info('Spider opened: %s' % spider.name)
然后在settings.py
中启用信号处理:
# settings.py
SPIDER_MIDDLEWARES = {
'myproject.middlewares.MySpiderMiddleware': 543,
}
通过上述方法,你可以根据需要修改Scrapy的行为。根据你的具体需求,可以进一步探索Scrapy的文档和源码,了解更多高级用法。