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

持久化存储可根据具体需求去做

原文地址:https://www.cnblogs.com/fengchong/p/10473402.html