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

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

相关推荐
缘友一世19 小时前
PyCharm连接autodl平台服务(python解释器&jupyter lab)
python·jupyter·pycharm
a程序小傲19 小时前
得物Java面试被问:方法句柄(MethodHandle)与反射的性能对比和底层区别
java·开发语言·spring boot·后端·python·面试·职场和发展
华研前沿标杆游学20 小时前
2026走进滕讯:小游戏×大模型产业交流记
python
_codemonster20 小时前
计算机视觉入门到实战系列(八)Harris角点检测算法
python·算法·计算机视觉
默默前行的虫虫20 小时前
nicegui的3D可视化
python
hui函数20 小时前
Python系列Bug修复|如何解决 pip install -e . 安装报错 “后端不支持可编辑安装(PEP 660)” 问题
python·bug·pip
二哈喇子!20 小时前
PyTorch与昇腾平台算子适配:从注册到部署的完整指南
人工智能·pytorch·python
FPGAI20 小时前
Python之函数
开发语言·python
七夜zippoe20 小时前
领域驱动设计在Python中的实现:从理论到生产级实践
数据库·python·sqlite·ddd·pydantic
TG_imqfxt66620 小时前
虚拟机下安装苹果系统,虚拟机下如何实现协议群发iMessage?
python·objective-c