基于scrapy的豆瓣阅读top250爬虫

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

一 、安装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就可以启动爬虫啦

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Scrapy是一个强大的Python网络爬虫框架,用于从网站上抓取数据。如果你想用它爬取豆瓣Top250电影排行榜的数据,可以按照以下步骤操作: 1. **安装Scrapy**:首先需要确保已经安装了Python以及Scrapy框架,如果没有,可通过`pip install scrapy`命令安装。 2. **创建项目**:运行`scrapy startproject douban_tops` 创建一个新的Scrapy项目,选择一个合适的名称。 3. **定义Spider**:在spiders文件夹下新建一个Python文件,如'doubantop.py',并定义一个继承自`DjangoSpider`或`BaseSpider`的爬虫类。设置起始URL(通常是豆瓣电影Top250的页面地址)和解析规则。 ```python import scrapy class DoubanTopSpider(scrapy.Spider): name = 'doubantop' allowed_domains = ['movie.douban.com'] start_urls = ['https://movie.douban.com/top250'] def parse(self, response): # 使用XPath 或 CSS选择器找到你需要的数据(比如电影标题、评分等) titles = response.css('div.item .title a::text').getall() ratings = response.css('span.rating_num::text').getall() for title, rating in zip(titles, ratings): yield { 'title': title, 'rating': rating, } # 如果有分页链接,继续请求下一页 next_page = response.css('a.next::attr(href)').get() if next_page is not None: yield response.follow(next_page, self.parse) ``` 4. **运行爬虫**:在项目的根目录下,通过`scrapy crawl doubantop` 命令运行爬虫Scrapy会开始下载网页并处理数据。 5. **保存数据**:默认情况下,Scrapy将数据存储为JSON或其他标准格式,你可以根据需求配置其保存位置或使用中间件处理数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值