scrapy框架爬取小说

1.创建一个名为xiaoshuo81zw的爬虫项目

2.创建 CrawlSpider模板 的代码
在这里插入图片描述

3.zww文件里的代码,爬取不同的小说修改start_urls里的网址就可以了,限81中文网

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class ZwwwSpider(CrawlSpider):
    name = 'zww'
    allowed_domains = ['81zw.us']
    #要提取的小说网站的章节列表
    start_urls = ['https://www.81zw.us/book/523/']

    #定义规则,rules可以存放多种规则,LinkExtractor:存放具体规则,callback:将链接放入parse_item解析,follow:是否跟进提取到的链接
    rules = (
        #r'//*[@id="list"]/dl/dd[1]/a'为第一章小说页面
        Rule(LinkExtractor(restrict_xpaths=r'//*[@id="list"]/dl/dd[1]/a'), callback='parse_item', follow=True),
        #r'//div[@class="bottem1"]/a[3]'为下一章标签
        Rule(LinkExtractor(restrict_xpaths=r'//div[@class="bottem1"]/a[3]'), callback='parse_item', follow=True),
    )
    #解析  response.xpath:以xpath方式解析,  .extract():字符串化, replace('    ', '\n'):将空格替换为换行
    def parse_item(self, response):
        title = response.xpath('//h1/text()').extract_first()
        content = ''.join(response.xpath('//div[@id="content"]/text()').extract()).replace('    ', '\n')
        
		#将解析的内容推送到pipelines
        yield {
            'title': title,             #小说章节名
            'content': content  #小说内容
        }


4.pipelines的代码

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


class Xiaoshuo81ZwPipeline(object):
    #将self的内容写入到本地
    def open_spider(self, spider):
        self.file = open('zsjq.txt', 'w', encoding='utf-8')
    #将推送的内容拼接写入self
    def process_item(self, item, spider):
        title = item['title']
        content = item['content']
        info = title + '\n' + content + '\n'
        self.file.write(info)
        self.file.flush()
        return item
    #关闭self
    def close_spider(self, spider):
        self.file.close()

5.修改settings文件

  1. 修改浏览器标识USER_AGENT
    在这里插入图片描述
  2. 将爬取限制关闭
    在这里插入图片描述
  3. 设置下载速度
    在这里插入图片描述
  4. 打开下载管道在这里插入图片描述

settings完整代码

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

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

BOT_NAME = 'xiaoshuo81zw'

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' \
             ' Chrome/66.0.3359.181 Safari/537.36'

# 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://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 2
# 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://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'xiaoshuo81zw.middlewares.Xiaoshuo81ZwSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#   'xiaoshuo81zw.middlewares.Xiaoshuo81ZwDownloaderMiddleware': 500,
#}

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

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
    'xiaoshuo81zw.pipelines.Xiaoshuo81ZwPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.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://docs.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'

6.创建文件main,添加运行代码,运行后即可爬取

from scrapy.cmdline import execute
execute(['scrapy','crawl','zww'])
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值