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

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

相关推荐
惜.己5 分钟前
使用python的读取xml文件,简单的处理成元组数组
xml·开发语言·python·测试工具
倔强青铜三13 分钟前
苦练Python第25天:玩转字典
人工智能·python·面试
倔强青铜三27 分钟前
苦练Python第23天:元组秘籍与妙用
人工智能·python·面试
Norvyn_71 小时前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
chao_7891 小时前
更灵活方便的初始化、清除方法——fixture【pytest】
服务器·自动化测试·python·pytest
心情好的小球藻2 小时前
Python应用进阶DAY9--类型注解Type Hinting
开发语言·python
都叫我大帅哥2 小时前
LangChain加载HTML内容全攻略:从入门到精通
python·langchain
惜.己2 小时前
使用python读取json数据,简单的处理成元组数组
开发语言·python·测试工具·json
都叫我大帅哥3 小时前
Python的Optional:让你的代码优雅处理“空值”危机
python
曾几何时`5 小时前
基于python和neo4j构建知识图谱医药问答系统
python·知识图谱·neo4j