scrapy实例三 【豆瓣电影Top250】

本篇文章可能基于管道的文件保存有点问题,可以关闭管道直接在终端保存数据
保存为json
scrapy crawl db -o ./douban.json
保存为csv
scrapy crawl db -o ./douban.csv
spider.py

import scrapy
from douban.items import DoubanItem
import re

class DbSpider(scrapy.Spider):
    name = 'db'
    allowed_domains = ['movie.douban.com']
    start_urls = ['https://movie.douban.com/top250']

    def parse(self, response):
        list_li=response.xpath('//*[@id="content"]/div/div[1]/ol/li')
        for item in list_li:
            douban_item=DoubanItem()
            #序号
            douban_item["serial_number"]=item.xpath('./div/div[1]/em/text()').extract_first()
            #电影名称
            douban_item["movie_name"]=item.xpath('./div/div[2]/div[1]/a/span[1]/text()').extract_first()
            #电影介绍
            douban_item["introduce"]= item.xpath('./div/div[2]/div[2]/p/text()').extract_first().strip().replace("\xa0","")
            # 星级
            douban_item["star"]=item.xpath('./div/div[2]/div[2]/div/span[2]/text()').extract_first()
            #评论数
            douban_item["evaluate"]=item.xpath('./div/div[2]/div[2]/div/span[4]/text()').extract_first()
            # 电影描述
            douban_item['describe']=item.xpath('./div/div[2]/div[2]/p[2]/span/text()').extract_first()

            items={
    
    
                "序号":douban_item["serial_number"],
                "电影名称":douban_item["movie_name"],
                "电影介绍":douban_item["introduce"],
                "星级":douban_item["star"],
                "评论数":douban_item["evaluate"],
                "电影描述":douban_item['describe'],
            }
            print(items)
            yield items

        # 翻页请求
        next_url=response.xpath('//*[@id="content"]/div/div[1]/div[2]/a/@href').extract()
        for i in next_url:
            yield scrapy.Request("https://movie.douban.com/top250"+i,callback=self.parse)




items.py

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

import scrapy


class DoubanItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    #序号
    serial_number=scrapy.Field()
    #电影名称
    movie_name=scrapy.Field()
    #电影介绍
    introduce=scrapy.Field()
    #星级
    star=scrapy.Field()
    #评论数
    evaluate=scrapy.Field()
    #电影描述
    describe=scrapy.Field()


pipelines.py

# 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


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter

import json
class DoubanPipeline:
    fp=None
    def open_spider(self,spider):
        self.fp=open('./douban.json','w',encoding='utf-8')
    def process_item(self, item, spider):
        json_itme=json.dumps(item,ensure_ascii=False)
        self.fp.write(json_itme+"\n")
        print(item)
        return item
    def close_spider(self,spider):
        self.fp.close()

settings.py

# Scrapy settings for douban 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 = 'douban'

SPIDER_MODULES = ['douban.spiders']
NEWSPIDER_MODULE = 'douban.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/89.0.4389.114 Safari/537.36'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False
LOG_LEVEL="ERROR"

# 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 = 0.5
# 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 = {
    
    
#    'douban.middlewares.DoubanSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
    
    
#    'douban.middlewares.DoubanDownloaderMiddleware': 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 = {
    
    
   'douban.pipelines.DoubanPipeline': 300,
}
FEED_EXPORTENCODING="utf-8"
# 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'

Guess you like

Origin blog.csdn.net/weixin_46457946/article/details/116137278