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

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

相关推荐
Dxy123931021623 分钟前
Python 装饰器详解
开发语言·python
ganjiee000739 分钟前
新电脑软件配置二:安装python,git, pycharm
python
Ronin-Lotus39 分钟前
程序代码篇---python向http界面发送数据
python·http
NaclarbCSDN1 小时前
Java IO框架
开发语言·python
Tom Boom1 小时前
19. 结合Selenium和YAML对页面实例化PO对象改造
python·测试开发·selenium·测试工具·自动化测试框架开发·po改造
一个Potato1 小时前
Python面试总结
开发语言·python
无敌最俊朗@1 小时前
**HTTP/HTTPS基础** - URL结构(协议、域名、端口、路径、参数、锚点) - 请求方法(GET、POST) - 请求头/响应头 - 状态码含义
爬虫·python·网络协议·http·https
xiaohanbao093 小时前
day29 python深入探索类装饰器
开发语言·python·学习·机器学习·pandas
CryptoRzz3 小时前
股票数据源对接技术指南:印度尼西亚、印度、韩国
数据库·python·金融·数据分析·区块链
胖哥真不错4 小时前
Python实现NOA星雀优化算法优化卷积神经网络CNN回归模型项目实战
python·cnn·卷积神经网络·项目实战·cnn回归模型·noa星雀优化算法