zoukankan      html  css  js  c++  java
  • 爬取4567电影网

    movie.py虫子

    # -*- coding: utf-8 -*-
    import scrapy
    from moviePro1.items import Moviepro1Item


    class MovieSpider(scrapy.Spider):
    name = 'movie'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['https://www.4567tv.tv/index.php/vod/show/class/喜剧/id/1.html']

    # 定义通用爬虫模板:
    url = "https://www.4567tv.tv/index.php/vod/show/class/喜剧/id/1/page/%d.html"

    page = 1

    # 用于解析电影名称:
    def parse(self, response):
    print("正在爬取第{}页的电影数据....".format(self.page))
    li_list = response.xpath('/html/body/div[1]/div/div/div/div[2]/ul/li')
    for li in li_list:
    item = Moviepro1Item()
    name = li.xpath('./div/a/@title').extract_first()
    item["name"] = name
    detail_url = 'https://www.4567tv.tv' + li.xpath('./div/a/@href').extract_first()

    # 对详情页url手动请求发送
    yield scrapy.Request(detail_url, callback=self.parse_detail,
    meta={"item": item}) # 让Request将一个数据值(字典的形式)传递给回调函数
    if self.page < 5:
    print("-----------------------------------------------------------")
    self.page += 1
    new_url = format(self.url % self.page)
    yield scrapy.Request(new_url, callback=self.parse)

    # 解析电影简介:
    def parse_detail(self, response):
    # 接收请求传参的数据(字典的形式)
    item = response.meta["item"]
    desc = response.xpath('/html/body/div[1]/div/div/div/div[2]/p[5]/span[3]/text()').extract_first()
    item["desc"] = desc
    yield item

    items.py

    # -*- coding: utf-8 -*-

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

    import scrapy


    class Moviepro1Item(scrapy.Item):
    # define the fields for your item here like:
    name = scrapy.Field()
    desc = scrapy.Field()

    middlewares.py

    # -*- coding: utf-8 -*-

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

    from scrapy import signals


    class Moviepro1SpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
    # This method is used by Scrapy to create your spiders.
    s = cls()
    crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
    return s

    def process_spider_input(self, response, spider):
    # Called for each response that goes through the spider
    # middleware and into the spider.

    # Should return None or raise an exception.
    return None

    def process_spider_output(self, response, result, spider):
    # Called with the results returned from the Spider, after
    # it has processed the response.

    # Must return an iterable of Request, dict or Item objects.
    for i in result:
    yield i

    def process_spider_exception(self, response, exception, spider):
    # Called when a spider or process_spider_input() method
    # (from other spider middleware) raises an exception.

    # Should return either None or an iterable of Request, dict
    # or Item objects.
    pass

    def process_start_requests(self, start_requests, spider):
    # Called with the start requests of the spider, and works
    # similarly to the process_spider_output() method, except
    # that it doesn’t have a response associated.

    # Must return only requests (not items).
    for r in start_requests:
    yield r

    def spider_opened(self, spider):
    spider.logger.info('Spider opened: %s' % spider.name)


    class Moviepro1DownloaderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
    # This method is used by Scrapy to create your spiders.
    s = cls()
    crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
    return s

    def process_request(self, request, spider):
    # Called for each request that goes through the downloader
    # middleware.

    # Must either:
    # - return None: continue processing this request
    # - or return a Response object
    # - or return a Request object
    # - or raise IgnoreRequest: process_exception() methods of
    # installed downloader middleware will be called
    return None

    def process_response(self, request, response, spider):
    # Called with the response returned from the downloader.

    # Must either;
    # - return a Response object
    # - return a Request object
    # - or raise IgnoreRequest
    return response

    def process_exception(self, request, exception, spider):
    # Called when a download handler or a process_request()
    # (from other downloader middleware) raises an exception.

    # Must either:
    # - return None: continue processing this exception
    # - return a Response object: stops process_exception() chain
    # - return a Request object: stops process_exception() chain
    pass

    def spider_opened(self, spider):
    spider.logger.info('Spider opened: %s' % spider.name)

    pipelines.py

    # -*- coding: utf-8 -*-

    # 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


    class Moviepro1Pipeline(object):
    def process_item(self, item, spider):
    print(item)
    return item

    settings.py

    # -*- coding: utf-8 -*-

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

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

    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'



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

    # 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 = 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 = {
    # 'moviePro1.middlewares.Moviepro1SpiderMiddleware': 543,
    #}

    # Enable or disable downloader middlewares
    # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
    #DOWNLOADER_MIDDLEWARES = {
    # 'moviePro1.middlewares.Moviepro1DownloaderMiddleware': 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 = {
    'moviePro1.pipelines.Moviepro1Pipeline': 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'
  • 相关阅读:
    PHP错误:Fatal error: session_start() 解决办法
    Flash 随机生成多个显示元件的ActionScript代码
    CMD 命令行查看端口被哪个程序占用,并根据PID值,找到相应的程序,关闭掉对应服务或进程!
    DB: 20 个数据库设计最佳实践
    ActionScript 3.0 组件!
    FLASH ActionScript 3.0 sns cocial game 开发中的定时器
    PHP 获取用户真实IP
    我想成为坐在路边鼓掌的人
    Mobile + Web 并举的Social Game开发模式
    addEventListener & removeEventListener || attachEvent & detachEvent
  • 原文地址:https://www.cnblogs.com/zhang-da/p/12432099.html
Copyright © 2011-2022 走看看