scrapy爬取名人名言

爬取名人名言:http://quotes.toscrape.com/

1 创建爬虫项目,在终端中输入:

python 复制代码
scrapy startproject quotes

2 创建之后,在spiders文件夹下面创建爬虫文件quotes.py,内容如下:

python 复制代码
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class Quotes(CrawlSpider):
    name = "quotes"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ['http://quotes.toscrape.com/']

    rules = (
        Rule(LinkExtractor(allow='/page/\d+'), callback='parse_quotes', follow=True),
        Rule(LinkExtractor(allow='/author/\w+'), callback='parse_author')
    )

    def parse_quotes(self, response):
        for quote in response.css('quote'):
            yield {
                'content': quote.css('.text::text').extract_first(),
                'author': quote.css('.author::text').extract_first(),
                'tags': quote.css('.tag::text').extract_first()
            }

    def parse_author(selfself, response):
        name = response.css('.author-title::text').extract_first()
        author_born_date = response.css('.author-born-date::text').extract_first()
        author_born_location = response.css('.author-born-location::text').extract_first()
        author_description = response.css('.author-description::text').extract_first()
        return ({
            'name': name,
            'author_born_date': author_born_date,
            'author_born_location': author_born_location,
            'author_description': author_description
        })

目录结构如下:

3 运行爬虫

在终端中执行scrapy crawl quotes,结果如图所示:

到此,一个简单的爬虫就完成了。

相关推荐
❁满城风絮*16 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天19 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读19 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户83562907805119 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
用户83562907805120 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
特立独行的猫A20 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
深蓝AI20 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP20 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
李帅5151 天前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python
happylifetree1 天前
Python79:核心语法-面向对象基础-实例方法
python