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

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

相关推荐
我叫汪枫38 分钟前
Python 办公自动化入门:玩转 Excel 与 Word
python·word·excel
E_ICEBLUE44 分钟前
三步完成 Markdown 到 Word/PDF 的转换:Python 教程
python·pdf·word·markdown·格式转换
后台开发者Ethan2 小时前
LangGraph ReAct应用
python·langgraph
f***68602 小时前
问题:Flask应用中的用户会话(Session)管理失效
后端·python·flask
爱吃面条的猿2 小时前
Python修改pip install 指定安装包的路径和默认镜像源
linux·python·pip
饭饭大王6662 小时前
Python 模块的概念与导入:从基础语法到高级技巧
java·服务器·python
Sunhen_Qiletian2 小时前
python语言应用实战--------网络爬虫篇 第二篇(selenium库)
爬虫·python·selenium
鄃鳕3 小时前
装饰器【Python】
开发语言·python·数码相机
m0_528489254 小时前
Pycharm修改系统缓存路径(包含config, system, plugins, logs, remote sources等)
ide·python·pycharm·c盘