使用scrapy+mongodb爬取豆瓣电影TOP250

来源:互联网 发布:知乎 陈毅 编辑:程序博客网 时间:2024/04/30 02:24

使用了class scrapy.spiders.CrawlSpider
rules
一个包含一个(或多个) Rule 对象的集合(list)。 每个 Rule 对爬取网站的动作定义了特定表现。 Rule对象在下边会介绍。 如果多个rule匹配了相同的链接,则根据他们在本属性中被定义的顺序,第一个会被使用。
parse_start_url(response)
当start_url的请求返回时,该方法被调用。 该方法分析最初的返回值并必须返回一个 Item 对象或者 一个 Request 对象或者 一个可迭代的包含二者对象。
爬取规则(Crawling rules)

class scrapy.spiders.Rule(link_extractor, callback=None, cb_kwargs=None, follow=None, process_links=None, process_request=None)
  • link_extractor 是一个 Link Extractor 对象。 其定义了如何从爬取到的页面提取链接。
  • callback 是一个callable或string(该spider中同名的函数将会被调用)。从link_extractor中每获取到链接时将会调用该函数。该回调函数接受一个response作为其第一个参数, 并返回一个包含Item 以及(或) Request 对象(或者这两者的子类)的列表(list)。

    警告

    当编写爬虫规则时,请避免使用 parse 作为回调函数。 由于 CrawlSpider 使用 parse 方法来实现其逻辑,如果 您覆盖了
    parse 方法,crawl spider 将会运行失败。

  • cb_kwargs 包含传递给回调函数的参数(keyword argument)的字典。
  • follow 是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果 callback为None, follow 默认设置为 True ,否则默认为 False 。
  • process_links 是一个callable或string(该spider中同名的函数将会被调用)。从link_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。
  • process_request 是一个callable或string(该spider中同名的函数将会被调用)。该规则提取到每个request时都会调用该函数。该函数必须返回一个request或者None。 (用来过滤request)

items.py

import scrapyfrom scrapy.item import Item,Fieldclass DoubanmovieItem(scrapy.Item):    # define the fields for your item here like:    # name = scrapy.Field()    name=Field()    year=Field()    score=Field()    director=Field()    classification=Field()    actor=Field()

spiders.py

# -*- coding:utf-8 -*-from scrapy.selector import Selectorfrom scrapy.spiders import CrawlSpider,Rulefrom scrapy.linkextractors import LinkExtractorfrom doubanmovie.items import DoubanmovieItemclass MovieSpider(CrawlSpider):    name="doubanmovie"    allowed_domains=['movie.douban.com']    start_urls=['http://movie.douban.com/top250']    rules=[        Rule(LinkExtractor(allow=(r'http://movie.douban.com/top250\?start=\d+.'))),        Rule(LinkExtractor(allow=(r'http://movie.douban.com/subject/\d+')),callback="parse_item"),        ]    def parse_item(self,response):        sel=Selector(response)        item=DoubanmovieItem()        item['name']=sel.xpath('//*[@id="content"]/h1/span[1]/text()').extract()        item['year']=sel.xpath('//*[@id="content"]/h1/span[2]/text()').re(r'\((\d+)\)')        item['score']=sel.xpath('//*[@id="interest_sectl"]/div/p[1]/strong/text()').extract()        item['director']=sel.xpath('//*[@id="info"]/span[1]/a/text()').extract()        item['classification']= sel.xpath('//span[@property="v:genre"]/text()').extract()        item['actor']= sel.xpath('//*[@id="info"]/span[3]/a[1]/text()').extract()        return item

使用mongodb保存
pipelines.py

from pymongo import MongoClientfrom scrapy.exceptions import DropItemfrom scrapy.conf import settingsfrom scrapy import logclass DoubanmoviePipeline(object):    def __init__(self):                    client=MongoClient(settings['MONGODB_SERVER'],settings['MONGODB_PORT'])        db=client[settings['MONGODB_DB']]        self.collection=db[settings['MONGODB_COLLECTION']]    def process_item(self, item, spider):        valid=True        for data in item:            if not data:                valid=False                raise DropItem("Missing %s of blogpost from %s"%(data,item['url']))        if valid:            new_movie=[{                "name":item['name'][0],                "year":item['year'][0],                "score":item['score'][0],                "director":item['director'],                "classification":item['classification'],                "actor":item['actor']            }]            self.collection.insert(new_movie)            log.msg("Item wrote to MongoDB database %s/%s"%(settings['MONGODB_DB'],settings['MONGODB_COLLECTION']),level=log.DEBUG,spider=spider)        return item

在settings中设置一下
settings.py

ITEM_PIPELINES = {    'doubanmovie.pipelines.DoubanmoviePipeline': 300,}LOG_LEVEL='DEBUG'DOWNLOAD_DELAY=2RANDOMIZE_DOWNLOAD_DELAY=TrueUSER_AGENT='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.54 Safari/536.5'COOKIES_ENABLED=TrueMONGODB_SERVER = 'localhost'MONGODB_PORT = 27017MONGODB_DB = 'python'MONGODB_COLLECTION = 'test'