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,结果如图所示:

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

相关推荐
巴里巴气1 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19892 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金2 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python
ansurfen2 小时前
我的第一个AI项目:从零搭建RAG知识库的踩坑之旅
python·llm
前端付豪2 小时前
20、用 Python + API 打造终端天气预报工具(支持城市查询、天气图标、美化输出🧊
后端·python
前端付豪2 小时前
19、用 Python + OpenAI 构建一个命令行 AI 问答助手
后端·python
amazinging2 小时前
北京-4年功能测试2年空窗-报培训班学测开-第四十三天
python·学习
wgyang20163 小时前
我的第一个LangFlow工作流——复读机
python
Zhen (Evan) Wang3 小时前
(豆包)xgb.XGBRegressor 如何进行参数调优
开发语言·python
我爱一条柴ya3 小时前
【AI大模型】线性回归:经典算法的深度解析与实战指南
人工智能·python·算法·ai·ai编程