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

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

相关推荐
mortimer6 小时前
如何解决 uv run 因网络问题导致的 Python 下载失败
python·github
电子_咸鱼7 小时前
高阶数据结构——并查集
数据结构·c++·vscode·b树·python·算法·线性回归
生信大杂烩7 小时前
Xenium数据分析 | 使用Xenium Ranger重新分析数据
python·数据分析
郁大锤7 小时前
OpenAI responses使用教程(三) ——Responses create python SDK 介绍
人工智能·python·ai·openai
hardmenstudent7 小时前
Python字典--第1关:元组使用:这份菜单能修改吗?
开发语言·python
再__努力1点7 小时前
【02】深入理解Harris角点检测:从原理推导到实战实现
python·opencv·计算机视觉·特征提取
moeyui7058 小时前
Python文件编码读取和处理整理知识点
开发语言·前端·python
程序员爱钓鱼8 小时前
Python编程实战 - Python实用工具与库 - 正则表达式匹配(re 模块)
后端·python·面试
程序员爱钓鱼8 小时前
Python编程实战 - Python实用工具与库 - 爬取并存储网页数据
后端·python·面试