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

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

相关推荐
e***74957 小时前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
Ace_31750887767 小时前
京东商品详情接口终极突破:从多接口联动解析到数据全息重构
python·重构
汗流浃背了吧,老弟!7 小时前
Langchian检索YouTube视频字幕
python·音视频
励志前端小黑哥8 小时前
uv包管理器--python也有自己的pnpm了
开发语言·python·uv
2501_941112078 小时前
深入理解Python的if __name__ == ‘__main__‘
jvm·数据库·python
2501_941112058 小时前
Python Lambda(匿名函数):简洁之道
jvm·数据库·python
小兵张健8 小时前
Java + Spring 到 Python + FastAPI (三)
python·spring·fastapi
阿龍17878 小时前
媒体文件问题检测脚本(一)(python+ffmpeg)
开发语言·python
速易达网络8 小时前
flask与fastapi的区别
python
ycydynq8 小时前
python html 解析的一些写法
linux·python·html