Scrapy 實現爬取多頁數據 + 多層url數據爬取


項目需求:爬取https://www.4567tv.tv/frim/index1.html網站前三頁的電影名稱和電影的導演名稱

項目分析:電影名稱在初次發的url返回的response中可以獲取,可以通過對url進行字符串拼接的方式動態獲取前三頁的url,但是導演名稱必須點擊具體電影的鏈接地址才可以得到,所以第一次url返回的response中一定包含電影詳情的鏈接,通過數據解析的方式獲取電影詳情鏈接,再次對電影的詳情鏈接發起請求,得到相關的導演數據

爬蟲文件起名為movie.py

import scrapy
from moviePro.items import MovieproItem

class MovieSpider(scrapy.Spider):
    name = 'movie'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.4567tv.tv/frim/index1.html']

    page = 1
    page_url = "https://www.4567tv.tv/frim/index1-%s.html"
    #解析詳情頁中的數據
    def parse_detail(self,response):
        #response.meta返回接收到的meta字典
        item = response.meta['item']
        actor = response.xpath('/html/body/div[1]/div/div/div/div[2]/p[3]/a/text()').extract_first()
        item['actor'] = actor

        yield item
        #總結:兩個地方會用到item
        #第一用yield 返回item
        #第二用yield手動發起Requets請求或者是FormRequests請求

    def parse(self, response):
        li_list = response.xpath('//li[@class="col-md-6 col-sm-4 col-xs-3"]')
        for li in li_list:
            item = MovieproItem()     #實例化item對象
            name = li.xpath('./div/a/@title').extract_first()
            detail_url = 'https://www.4567tv.tv'+li.xpath('./div/a/@href').extract_first()
            item['name'] = name
            #meta參數:請求傳參.meta字典就會傳遞給回調函數的response參數
            #在解析過程中產生新的url,需要對新的url再次發起請求時,yield 手動調用scrapy.Request方法對象,
            yield scrapy.Request(url=detail_url,callback=self.parse_detail,meta={'item':item})

        #獲取前三頁的數據
        if self.page <= 3:
            self.page += 1
            new_page_url = self.page_url % self.page

            yield scrapy.Request(url=new_page_url,callback=self.parse)
import scrapy


class MovieproItem(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    actor = scrapy.Field()
items.py

持久化存儲可根據具體需求去做


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM