scrapy框架实现异步存储mysql数据库,今天案例是爬取顶点小说网,title,author,type,cover,intro,id

本文介绍了一种使用Scrapy框架抓取小说网站数据的方法,包括小说标题、作者、类型、封面图片、简介及唯一ID。通过详细代码示例,展示了如何配置Scrapy项目,设置爬虫规则,以及如何将抓取到的数据异步存入MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里今天只爬取一个分类,想要抓取所有小说的朋友,可以修改一下取的标签就可以了;

废话不多说了,我们先安装一下MySQLdb:

执行命令是:pip install mysqlclient

                  :pip install pymysql

上面的配置好之后我们就直接上代码了:::

 

spider.py

# -*- coding: utf-8 -*-
import scrapy
from ..items import DingdianItem

class DdSpider(scrapy.Spider):
    name = 'dd'
    allowed_domains = ['dingdian.com']
    start_urls = ['https://www.booktxt.net/xiaoshuodaquan/']

    def parse(self, response):
        """
        获取每部小说链接地址
        :param response:
        :return:
        """
        novel_list = response.xpath("//div[@class='novellist'][6]//ul//li/a/@href").extract()
        # print('***************************************************', novel_list)
        for novel in novel_list:
            url = novel
            yield scrapy.Request(url=url, callback=self.parse2, dont_filter=True, meta={"each_url":url})

    def parse2(self, response):
        """
        获取每部小说详情链接
        :param response:
        :return:
        """
        each_url = response.meta["each_url"]
        """名称"""
        title = response.xpath("//div[@class='box_con']/div[@id='maininfo']//h1/text()").extract_first()
        """作者"""
        author = response.xpath("//div[@class='box_con']/div[@id='maininfo']//p/text()").extract_first().split(":")[-1]
        """类型"""
        type = response.xpath("normalize-space(//div[@id='wrapper']//div[@class='con_top'])").extract_first().split(" > ")[1]
        """图片"""
        cover = 'https://www.booktxt.net' + response.xpath("//div[@id='wrapper']/div[@class='box_con']//div[@id='fmimg']/img/@src").extract_first()
        """简介"""
        intro = response.xpath("normalize-space(//div[@id='wrapper']/div[@class='box_con']//div[@id='intro']/p/text())").extract_first()
        """唯一id"""
        fiction_id = response.url.split("/")[-2]

        item = DingdianItem()

        item['title'] = title
        item['author'] = author
        item['type'] = type
        item['cover'] = cover
        item['intro'] = intro
        item["fiction_id"] = fiction_id

        yield item

items.py

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy


class DingdianItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    title = scrapy.Field()
    author = scrapy.Field()
    type = scrapy.Field()
    cover = scrapy.Field()
    intro = scrapy.Field()
    fiction_id = scrapy.Field()
    pass

settings.py

# -*- coding: utf-8 -*-

# Scrapy settings for dingdian project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://doc.scrapy.org/en/latest/topics/settings.html
#     https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://doc.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'dingdian'

SPIDER_MODULES = ['dingdian.spiders']
NEWSPIDER_MODULE = 'dingdian.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'dingdian (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# 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_ENABLED = False

# 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 = {
#    'dingdian.middlewares.DingdianSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'dingdian.middlewares.DingdianDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://doc.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://doc.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'dingdian.pipelines.DingdianPipeline': 300,
}
MYSQL_HOST = '127.0.0.1'
MYSQL_PORT = 3306
MYSQL_USER = "root"
MYSQL_PASSWORD = "123456"
MYSQL_CHARSET = "utf8"
MYSQL_DBNAME = "fiction_2"



# 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'
#

pipelines.py

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
from MySQLdb.cursors import DictCursor
import hashlib

"""定义一个异步存储至mysql的pipeline
scrapy的解析是异步多线程的,解析速度非常快,而mysql的execute()和commit()提交数据库的方式是同步的,所有数据库写入速度比较慢
一旦数量较大,可能会导致item中断插入不及时,造成数据库写入堵塞,最终导致数据库卡死或数据丢失,所以需要使用数据库的异步写入
"""


class DingdianPipeline(object):
    def __init__(self, dbpool):
        # 初始化线程池对象
        self.dbpool = dbpool

    @classmethod
    def from_crawler(cls, crawler):
        args = dict(host=crawler.settings.get("MYSQL_HOST"), port=crawler.settings.get("MYSQL_PORT"),
                    user=crawler.settings.get("MYSQL_USER"), db=crawler.settings.get("MYSQL_DBNAME"),
                    passwd=crawler.settings.get("MYSQL_PASSWORD"), charset=crawler.settings.get("MYSQL_CHARSET"),
                    cursorclass=DictCursor)
        # 创建一个线程池对象
        # 参数一:用于连接mysql数据库的驱动的名称
        # 相当于同时创建了含有很多个线程池对象(游标或者数据库连接)
        dbpool = adbapi.ConnectionPool("MySQLdb", **args)
        print('链接成功**************************************************************',dbpool)
        return cls(dbpool)

    def insert_sql(self, cursor, item):
        inser_sql = "insert into home_fiction(title, author, type, cover, intro, fiction_id)values ('%s','%s','%s'," \
                    "'%s','%s','%s') on duplicate key update title=(title)" % (item["title"], item["author"], item["type"], item["cover"],
                                         item["intro"], item["fiction_id"])
        cursor.execute(inser_sql)

    def process_item(self, item, spider):
        """
        在线程池dbpool中通过runInteraction()函数,来实现异步插入数据的操作,runInteraction()会将inser_sql这个函数交给线程池中的某一个线程具体执行.
        :param item:
        :param spider:
        :return:
        """
        result = self.dbpool.runInteraction(self.insert_sql, item)
        # 如果数据插入失败,会执行addErrback()内部的函数调用
        result.addErrback(self.error_info)

    def error_info(self, failure):
        print("数据插入失败,原因是:", failure)

以上就是所有代码,有什么问题或者这个代码有什么bug,欢迎指教

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值