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