Scrapy爬虫框架Spiders爬虫脚本使用技巧

我们都知道Scrapy是一个用于爬取网站数据、提取结构化数据的Python框架。在Scrapy中,Spiders是用户自定义的类,用于定义如何爬取某个(或某些)网站,包括如何执行爬取(即跟踪链接)以及如何从页面中提取结构化数据(即爬取项)。至于如何定义Spiders爬虫逻辑和规则可以看看我下面总结的经验。

Scrapy 是一个强大的 Python 爬虫框架,其核心组件 Spiders 用于定义爬取逻辑和数据提取规则。下面是一个详细的结构解析和示例:

一、Scrapy Spider 核心组件

  1. 类定义 :继承 scrapy.Spider 或其子类

  2. 必要属性

    • name:爬虫唯一标识符
    • start_urls:初始爬取 URL 列表
  3. 核心方法

    • parse(self, response):默认回调函数,处理响应并提取数据
  4. 可选扩展

    • 自定义设置(custom_settings
    • 链接跟踪规则(CrawlSpider

二、基础 Spider 示例

css 复制代码
import scrapy
​
class BookSpider(scrapy.Spider):
    name = "book_spider"
    start_urls = ["http://books.toscrape.com/"]
​
    def parse(self, response):
        # 提取书籍列表页数据
        for book in response.css("article.product_pod"):
            yield {
                "title": book.css("h3 a::attr(title)").get(),
                "price": book.css("p.price_color::text").get(),
                "rating": book.css("p.star-rating::attr(class)").get().split()[-1]
            }
​
        # 跟踪下一页
        next_page = response.css("li.next a::attr(href)").get()
        if next_page:
            yield response.follow(next_page, callback=self.parse)

三、进阶 CrawlSpider 示例(自动链接跟踪)

css 复制代码
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
​
class AdvancedSpider(CrawlSpider):
    name = "crawl_spider"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/catalog"]
    
    # 定义链接提取规则
    rules = (
        # 匹配商品详情页(回调函数处理)
        Rule(LinkExtractor(restrict_css=".product-item"), callback="parse_item"),
        
        # 匹配分页链接(无回调默认跟随)
        Rule(LinkExtractor(restrict_css=".pagination"))
    )
​
    def parse_item(self, response):
        yield {
            "product_name": response.css("h1::text").get(),
            "sku": response.xpath("//div[@class='sku']/text()").get(),
            "description": response.css(".product-description ::text").getall()
        }

四、关键功能解析

组件 作用
response.css() 用 CSS 选择器提取数据(推荐 ::text/::attr(xxx)
response.xpath() XPath 选择器,处理复杂结构
response.follow() 自动处理相对 URL 的请求生成
LinkExtractor 自动发现并跟踪链接,支持正则/CSS/XPath 过滤
custom_settings 覆盖全局配置(如:DOWNLOAD_DELAY, USER_AGENT

五、最佳实践

  1. 数据管道

    • pipelines.py 中定义数据清洗/存储逻辑
    • settings.py 启用管道:ITEM_PIPELINES
  2. 中间件

    • 下载中间件处理请求头/代理/IP轮换

    • 示例代理中间件:

      ruby 复制代码
      class ProxyMiddleware:
          def process_request(self, request, spider):
              request.meta["proxy"] = "http://proxy_ip:port"
  3. 防反爬策略

    • 随机 User-Agent:scrapy-fake-useragent
    • 自动限速:AUTOTHROTTLE_ENABLED = True

六、运行与调试

  1. 启动爬虫

    复制代码
    scrapy crawl book_spider -o books.json
  2. Shell 调试

    csharp 复制代码
    scrapy shell "http://books.toscrape.com"
    >>> response.css('h1::text').get()

七、常见问题解决

  • 403 禁止访问 :添加合法 USER_AGENT
  • 数据缺失 :检查目标页面动态加载(需启用 scrapy-splashselenium 中间件)
  • 重复 URL :启用去重中间件 DUPEFILTER_CLASS

如果掌握上面这些核心模式后,大体上就可以灵活应对各类网站爬取需求。但是也要建议多结合Scrapy 官方文档多多学习。

相关推荐
杨荧4 天前
基于Python的宠物服务管理系统 Python+Django+Vue.js
大数据·前端·vue.js·爬虫·python·信息可视化
上海云盾第一敬业销售5 天前
小程序被爬虫攻击,使用waf能防护吗?
爬虫·小程序
小小码农一只5 天前
Python 爬虫实战:玩转 Playwright 跨浏览器自动化(Chromium/Firefox/WebKit 全支持)
爬虫·python·自动化
weixin_443353316 天前
小红书帖子评论的nodejs爬虫脚本
前端·爬虫
TLuoQiu7 天前
小电视视频内容获取GUI工具
爬虫·python
麦麦大数据7 天前
F004 新闻可视化系统爬虫更新数据+ flask + mysql架构
爬虫·mysql·flask·可视化·新闻
python-行者7 天前
akamai鼠标轨迹
爬虫·python·计算机外设·akamai
NEUMaple8 天前
python爬虫(四)----requests
开发语言·爬虫·python
电商API_180079052478 天前
大规模调用淘宝商品详情 API 的分布式请求调度实践
服务器·数据库·分布式·爬虫
小白学大数据8 天前
1688商品数据抓取:Python爬虫+动态页面解析
爬虫·python·okhttp