【Scrapy】基于scrapy的豆瓣阅读top250爬虫

Hello,这是我的第一篇博客,很久以前就开始学习爬虫了,不过处于反爬手段的策略,再加上之前的公司一直没有要求用scrapy,导致一直没有认真学习scrapy框架。现在有时间了,打算好好学一下这个框架。这篇博客是基于scrapy的豆瓣top250爬虫,以前是有写过top250电影的爬虫的。不过没用scrapy。。废话不多说,开始吧!!

的
scrapy工作流程

工作流程:

这里简单的介绍一下scrapy的工作原理:

1.首先我们在爬虫文件中定义的start_urls会被引擎读取出来传输给spider,spider会将url一一封装成request请求对象,并将request对象通过引擎传送给scheduler调度器。

2.scheduler调度器会将依次将request请求通过引擎传送给downloader下载器,下载器会去请求数据,然后将相应数据封装成response对象传送给引擎。中途还可以设置download middleware中间件自定义下载的一些操作。

3.接下来引擎再次将response对象传送给spider,我们可以设置spider解析数据的流程,如果是数据项是url,则让引擎再次传送给scheduler调度队列,再次重复之前的操作。如果数据项是item,则通过引擎传输给pipline。

4.pipline管道拿到引擎传输过来的数据后,就可以进行其他处理保存了。

因此我们可以看出,在scrapy中,request对象和response对象是非常重要的,我们所做的操作基本都离不开他们,而在yeild返回的对象中,也只能接收request对象,item对象,或者dict字典和空值。

一 、安装scrapy

这个很简单,直接pip install scrapy即可,建议大家使用清华源,会快很多,也可以直接用pycharm的interpreter安装。

二、生成scrapy项目结构

先在你想放爬虫的目录打开终端,输入scrapy startproject 项目名,这样就会自动生成scrapy项目结构。项目名任取,我这里取得是myspider

三、编写代码

这里直接附上我的代码,主要有三个地方需要自己编写,一个是在spider下面自己创建的爬虫文件,还有items,piplines。

  • 爬虫文件
import scrapy
from bs4 import BeautifulSoup

from ..items import MyspiderItem


class DoubanSpider(scrapy.Spider):
    name="douban"
    allowed_domains=['book.douban.com/top250']
    start_urls=['https://book.douban.com/top250']

    def parse(self, response, **kwargs):
        # beautifulsoup解析response的dom树
        bs=BeautifulSoup(response.text,"html.parser")
        # 根据tr标签找到每本书的信息
        tr_tag=bs.find_all("tr",class_="item")

        # 遍历每本书,读取书名,出版信息,热评
        for i in tr_tag:
            name=i.find_all("a")[1]["title"]
            info=i.find("p",class_="pl").text
            quote=i.find("span",class_="inq").text
            item=MyspiderItem()
            item["name"]=name
            item['info']=info
            item['quote']=quote

            # 返回给引擎
            yield item


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

import scrapy


class MyspiderItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    info = scrapy.Field()
    quote=scrapy.Field()
  • piplines
    # Define your item pipelines here
    #
    # Don't forget to add your pipeline to the ITEM_PIPELINES setting
    # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
    import openpyxl
    # useful for handling different item types with a single interface
    from itemadapter import ItemAdapter
    
    
    class MyspiderPipeline:
    
        def __init__(self):
            # 生成excel表
            self.workbook=openpyxl.Workbook()
            self.sheet=self.workbook.active
            self.sheet.append(["书名","介绍","热评"])
    
    
        def process_item(self, item, spider):
            # 将图书信息添加到excel表
            self.sheet.append([item["name"],item["info"],item['quote']])
            return item
    
        def close_spider(self,spider):
            self.workbook.save("book.xlsx")
            self.workbook.close()

四、修改相关配置

这一步主要关闭robots协议,还有启动piplines等

# Scrapy settings for myspider 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 = "myspider"

SPIDER_MODULES = ["myspider.spiders"]
NEWSPIDER_MODULE = "myspider.spiders"


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = "myspider (+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://docs.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",
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.76"}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    "myspider.middlewares.MyspiderSpiderMiddleware": 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "myspider.middlewares.MyspiderDownloaderMiddleware": 543,
#}

# 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 = {
   "myspider.pipelines.MyspiderPipeline": 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"

# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

五、启动项目

这里可以直接在终端输入scrapy crawl 爬虫名 来启动项目,不过我这里为了方便,引入了scrapy的cmdline,直接在py中调用cmd执行命令。直接在根目录下创建start.py

from scrapy import cmdline

cmdline.execute(["scrapy","crawl","douban"])

运行这个start.py就可以启动爬虫啦

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值