使用scrapy框架爬取豆瓣影评

本文介绍了一个基于Python 2.7的Scrapy框架实现的豆瓣电影评论爬虫项目。该项目详细展示了从创建项目到编写爬虫的具体步骤,并通过XPath解析网页数据,最终将抓取的数据保存为JSON文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近几天在看平凡岁月 感觉挺不错的一部生活剧,想看看豆瓣

对该据评论,使用scrapy爬取,基于python2.7进行实现

1. 创建scrapy项目
scrapy startproject doubanmovie
2.创建爬虫
scrapy genspider -t crawl dbm "movie.douban.com"

需要注意的是 爬虫名称不能和项目名称重复

3. 编写item

创建item

4.编写爬虫(spiders-->dbm.py)
# -*- coding: utf-8 -*-
import scrapy

from scrapy.linkextractors import LinkExtractor

from scrapy.spiders import CrawlSpider, Rule

from doubanmovie.items import DoubanmovieItem

class DbmSpider(CrawlSpider):
    name = 'dbm'
    allowed_domains = ['movie.douban.com']
    start_urls = ['https://movie.douban.com/subject/26795042/reviews?start=0']

    rules = (
        Rule(LinkExtractor(allow=r'start=\d+'), follow=True),
        Rule(LinkExtractor(allow=r'https://movie.douban.com/review/\d+/'), callback='parse_item', follow=False),
    )

    def parse_item(self, response):
        item = DoubanmovieItem()
        item['username'] = response.xpath("//header[@class='main-hd']/a/span/text()").extract()[0]
        title = response.xpath("//span[@property='v:summary']/text()").extract()[0]
        if len(title):
            item['title'] = title
        else:
            item['title'] = 'NULL'
        content = response.xpath("//div[@class='review-content clearfix']/p/text()").extract()
        if len(content):
            item['content'] = ''.join(content).strip()
        else:
            content = response.xpath("//div[@class='review-content clearfix']/text()").extract()
            if len(content):
                item['content'] = ''.join(content).strip()
            else:
                item['content'] = 'NULL'
        item['url'] = response.url
        yield item
5.编写管道文件(该案例使用json保存) doubanmovie->pipelines.py

import json
class YouyuanPipeline(object):
    def __init__(self):
        self.filename = open('youyuan.json','w')

    def process_item(self, item, spider):
        content = json.dumps(dict(item),ensure_ascii=False) + ',\n'
        self.filename.write(content.encode('utf-8'))
        return item

    def close_spider(self,spider):
        self.filename.close()
6.修改setting文件
USER_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'  
DOWNLOAD_DELAY = 3
ITEM_PIPELINES = {
   'doubanmovie.pipelines.DoubanmoviePipeline': 300,
}

7- 执行爬虫

scrapy crawl dbm

转载于:https://my.oschina.net/u/3273360/blog/1579179

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值