1. 程式人生 > 其它 >爬蟲_scrapy_多級頁面的資料爬取

爬蟲_scrapy_多級頁面的資料爬取

本案例以爬取電影天堂第一級頁面的電影名稱和點選連結後二級頁面的img地址,並將第一級的名稱和第二級頁面的圖片地址一起寫入json檔案,涉及到多級頁面資料的組合。

建立專案和頁面命令這裡就不說了,可以參考我之前的文章,這裡主要說明核心程式碼。

1.spiders下的mv.py程式碼

import scrapy
from scrapy_movie.items import ScrapyMovieItem
# 電影天堂多頁資料下載
class MvSpider(scrapy.Spider):
    name = 'mv'
    allowed_domains = ['www.dytt8.net
'] start_urls = ['https://www.dytt8.net/html/gndy/china/index.html'] def parse(self, response): # 要第一頁的名字和第二頁的圖片 a_list = response.xpath('//div[@class="co_content8"]//td[2]//a[2]') for a in a_list: # 獲取第一頁的name 和 要點選的連線 name = a.xpath('./text()').extract_first() href
= a.xpath('./@href').extract_first() # 第二頁的地址 url = 'https://www.dytt8.net'+href # 對第二頁的連結發起訪問 # 呼叫點選的頁面發起請求,並將已經獲取的name通過meta字典傳遞給parse_second方法 yield scrapy.Request(url=url,callback=self.parse_second,meta={'name':name}) def parse_second(self,response):
# 點選進入裡邊頁面的圖片地址 # 注意 如果拿不到資料的情況下,一定檢查你的xpath語法是否正確 src = response.xpath('//div[@id="Zoom"]//img/@src').extract_first() print(src) # 接收meta傳遞過來的引數值 name = response.meta['name'] # 建立解析物件 movie = ScrapyMovieItem(name=name,src=src) # 返回給管道 yield movie

2.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 ScrapyMovieItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    src = scrapy.Field()
    pass

3.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

# 管道
class ScrapyMoviePipeline:
    # 在爬蟲檔案開始的之前就執行這個方法
    def open_spider(self,spider):
        self.fp = open('movie.json','w',encoding='utf-8')
    # item就是yield後面的物件
    def process_item(self, item, spider):
        # 資料處理,寫檔案
        # write方法只能寫字串,需要強轉
        self.fp.write(str(item))
        return item
    # 在爬蟲檔案執行完成後,執行的方法
    def close_spider(self,spider):
        self.fp.close()

4.settings.py配置

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

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


# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'scrapy_movie (+http://www.yourdomain.com)'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# 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',
#}

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

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'scrapy_movie.middlewares.ScrapyMovieDownloaderMiddleware': 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 = {
   'scrapy_movie.pipelines.ScrapyMoviePipeline': 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'

執行結果:

 程式碼地址:https://gitee.com/heating-cloud/python_spider.git