我们都知道Scrapy是一个用于爬取网站数据、提取结构化数据的Python框架。在Scrapy中,Spiders是用户自定义的类,用于定义如何爬取某个(或某些)网站,包括如何执行爬取(即跟踪链接)以及如何从页面中提取结构化数据(即爬取项)。至于如何定义Spiders爬虫逻辑和规则可以看看我下面总结的经验。
Scrapy 是一个强大的 Python 爬虫框架,其核心组件 Spiders 用于定义爬取逻辑和数据提取规则。下面是一个详细的结构解析和示例:
scrapy.Spider
或其子类name
:爬虫唯一标识符start_urls
:初始爬取 URL 列表parse(self, response)
:默认回调函数,处理响应并提取数据custom_settings
)CrawlSpider
)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)
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) |
pipelines.py
中定义数据清洗/存储逻辑settings.py
启用管道:ITEM_PIPELINES
scrapy-fake-useragent
库AUTOTHROTTLE_ENABLED = True
USER_AGENT
scrapy-splash
或 selenium
中间件)DUPEFILTER_CLASS
如果掌握上面这些核心模式后,大体上就可以灵活应对各类网站爬取需求。但是也要建议多结合Scrapy 官方文档多多学习。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。