Scrapy盗墓笔记爬虫0.1版 保存到数据库mongode

2024-01-12 03:59

本文主要是介绍Scrapy盗墓笔记爬虫0.1版 保存到数据库mongode,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这次的实例是用scrapy对盗墓笔记进行爬取,并且通过数据库mongode进行连接,这里对数据库的可视化工具为:Robo 3T 1.1.1

环境: win10 py3.6 scrapy1.6
编译器: pycharm

main.py

from scrapy import cmdline
cmdline.execute('scrapy crawl dmoz'.split())

items.py

# -*- coding: utf-8 -*-# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.htmlimport scrapyclass NoverspiderItem(scrapy.Item):# 书名bookName = scrapy.Field()# 书标题bookTitle = scrapy.Field()# 章节数chapterNum = scrapy.Field()# 章节的名字chapterName = scrapy.Field()# 章节urlchapterURL = scrapy.Field()

pipelines.py

from Noverspider.items import  NoverspiderItem
from scrapy.conf import settings   # 配置项的使用
import pymongo                     # 导入python控制数据库mongode的包class NoverspiderPipeline(object):def __init__(self):            # 类的初始化 这里连接的数据库是没有上任何密码的host = settings['MONGODE_HOST']port = settings['MONGODE_PORT']dbName = settings['MONGODE_DBNAME']client = pymongo.MongoClient(host=host, port=port)tdb = client[dbName]self.post = tdb[settings['MONGODE_DOCNAME']]# 将返回的类似字典类型的items插入到数据库中def process_item(self, item, spider):bookInfo = dict(item)self.post.insert(bookInfo)return item

setting.py

# -*- coding: utf-8 -*-# 第七行都是scrapy自己生成的东西 这里不需要另外配置
BOT_NAME = 'Noverspider'    # 项目的名字 创建工程的时候会自动赋值SPIDER_MODULES = ['Noverspider.spiders']
NEWSPIDER_MODULE = 'Noverspider.spiders'
ITEM_PIPELINES = ['Noverspider.pipelines.NoverspiderPipeline']# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'Noverspider (+http://www.yourdomain.com)'# Obey robots.txt rules
ROBOTSTXT_OBEY = False# 下载时候的并发请求
# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16# Disable cookies (enabled by default) 禁用cookies
COOKIES_ENABLED = True
# 连接数据库的配置
MONGODE_HOST = '127.0.0.1'
MONGODE_PORT = 27017
MONGODE_DBNAME = 'Test'
MONGODE_DOCNAME = 'Book'
# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}# Enable or disable spider middlewares
# See https://doc.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'Noverspider.middlewares.NoverspiderSpiderMiddleware': 543,
#}# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'Noverspider.middlewares.NoverspiderDownloaderMiddleware': 543,
#}# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}# 配置项目管道 也就是pipilines吧,反正爬取这类东西的时候都得开启
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {'Noverspider.pipelines.NoverspiderPipeline': 300,
}# Enable and configure the AutoThrottle extension (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False# Enable and configure HTTP caching (disabled by default)
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

Noverspider.py

from scrapy.spiders import Spider
from Noverspider.items import NoverspiderItem   # 导入items中的类class Novspider(Spider):name = 'dmoz'# 需要爬取的url列表start_urls = ['http://www.daomubiji.com/dao-mu-bi-ji-1', 'http://www.daomubiji.com/dao-mu-bi-ji-2','http://www.daomubiji.com/dao-mu-bi-ji-3', 'http://www.daomubiji.com/dao-mu-bi-ji-4','http://www.daomubiji.com/dao-mu-bi-ji-5', 'http://www.daomubiji.com/dao-mu-bi-ji-6','http://www.daomubiji.com/dao-mu-bi-ji-7', 'http://www.daomubiji.com/dao-mu-bi-ji-8','http://www.daomubiji.com/dao-mu-bi-ji-2015','http://www.daomubiji.com/sha-hai','http://www.daomubiji.com/zang-hai-hua']def parse(self, response):# 类的初始化item = NoverspiderItem()# 获取书的名字bookName = response.xpath('//div[@class="container"]/h1/text()').extract()# 先抓大后抓小 这里是抓的章节的大Chapter = response.xpath('//div[@class="excerpts"]')content = Chapter.xpath('.//article/a/text()').extract()# 用每一个url作为下一个for循环的条件url = Chapter.xpath('.//article/a/@href').extract()# 循环提取盗墓笔记中需要的内容for i in range(len(url)):try:item['bookName'] = bookName[0].split(':')[0]item['bookTitle'] = bookName[0].split(':')[1]except Exception as e:item['bookName'] = bookName[0]item['chapterURL'] = url[i]try:item['chapterNum'] = content[i].split(' ')[1]item['chapterName'] = content[i].split(' ')[2]except Exception as e:item['chapterNum'] = content[i].split(' ')[1]yield item

获取到的数据:
数据
ps: 这里是极客学院的爬虫入门课程,由于那个视频已经老了,网站的结构已经发生了改变,这里重新编写的代码。
123

这篇关于Scrapy盗墓笔记爬虫0.1版 保存到数据库mongode的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/596733

相关文章

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

如何通过try-catch判断数据库唯一键字段是否重复

《如何通过try-catch判断数据库唯一键字段是否重复》在MyBatis+MySQL中,通过try-catch捕获唯一约束异常可避免重复数据查询,优点是减少数据库交互、提升并发安全,缺点是异常处理开... 目录1、原理2、怎么理解“异常走的是数据库错误路径,开销比普通逻辑分支稍高”?1. 普通逻辑分支 v

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

Go语言连接MySQL数据库执行基本的增删改查

《Go语言连接MySQL数据库执行基本的增删改查》在后端开发中,MySQL是最常用的关系型数据库之一,本文主要为大家详细介绍了如何使用Go连接MySQL数据库并执行基本的增删改查吧... 目录Go语言连接mysql数据库准备工作安装 MySQL 驱动代码实现运行结果注意事项Go语言执行基本的增删改查准备工作

MySQL 数据库表操作完全指南:创建、读取、更新与删除实战

《MySQL数据库表操作完全指南:创建、读取、更新与删除实战》本文系统讲解MySQL表的增删查改(CURD)操作,涵盖创建、更新、查询、删除及插入查询结果,也是贯穿各类项目开发全流程的基础数据交互原... 目录mysql系列前言一、Create(创建)并插入数据1.1 单行数据 + 全列插入1.2 多行数据

MySQL 数据库表与查询操作实战案例

《MySQL数据库表与查询操作实战案例》本文将通过实际案例,详细介绍MySQL中数据库表的设计、数据插入以及常用的查询操作,帮助初学者快速上手,感兴趣的朋友跟随小编一起看看吧... 目录mysql 数据库表操作与查询实战案例项目一:产品相关数据库设计与创建一、数据库及表结构设计二、数据库与表的创建项目二:员

Python学习笔记之getattr和hasattr用法示例详解

《Python学习笔记之getattr和hasattr用法示例详解》在Python中,hasattr()、getattr()和setattr()是一组内置函数,用于对对象的属性进行操作和查询,这篇文章... 目录1.getattr用法详解1.1 基本作用1.2 示例1.3 原理2.hasattr用法详解2.

MybatisPlus中removeById删除数据库未变解决方案

《MybatisPlus中removeById删除数据库未变解决方案》MyBatisPlus中,removeById需实体类标注@TableId注解以识别数据库主键,若字段名不一致,应通过value属... 目录MyBATisPlus中removeBypythonId删除数据库未变removeById(Se

在 Spring Boot 中连接 MySQL 数据库的详细步骤

《在SpringBoot中连接MySQL数据库的详细步骤》本文介绍了SpringBoot连接MySQL数据库的流程,添加依赖、配置连接信息、创建实体类与仓库接口,通过自动配置实现数据库操作,... 目录一、添加依赖二、配置数据库连接三、创建实体类四、创建仓库接口五、创建服务类六、创建控制器七、运行应用程序八