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

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

相关推荐
一点晖光44 分钟前
Docker 作图咒语生成器搭建指南
python·docker
smj2302_796826521 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
木头左1 小时前
位置编码增强法在量化交易策略中的应用基于短期记忆敏感度提升
python
Acc1oFl4g1 小时前
详解Java反射
java·开发语言·python
ney187819024743 小时前
分类网络LeNet + FashionMNIST 准确率92.9%
python·深度学习·分类
Data_agent3 小时前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法
2401_871260023 小时前
Java学习笔记(二)面向对象
java·python·学习
2301_764441334 小时前
使用python构建的应急物资代储博弈模型
开发语言·python·算法
喏喏心4 小时前
深度强化学习:价值迭代与Bellman方程实践
人工智能·python·学习·机器学习
小白勇闯网安圈4 小时前
supersqli、web2、fileclude、Web_python_template_injection
python·网络安全·web