当前位置: 移动技术网 > IT编程>脚本编程>Python > 基于python的scrapy框架爬取豆瓣电影及其可视化

基于python的scrapy框架爬取豆瓣电影及其可视化

2019年03月14日  | 移动技术网IT编程  | 我要评论

幼儿园托班育儿宝典,艳遇丽江 电影,千手纲手禁部照

1.scrapy框架介绍

scrapy

主要介绍,spiders,engine,scheduler,downloader,item pipeline

scrapy常见命令如下:

 

对应在scrapy文件中有,自己增加爬虫文件,系统生成items,pipelines,setting的配置文件就这些。

items写需要爬取的属性名,pipelines写一些数据流操作,写入文件,还是导入数据库中。主要爬虫文件写domain,属性名的xpath,在每页添加属性对应的信息等。

    movierank = scrapy.field()
    moviename = scrapy.field()
    director = scrapy.field()
    moviedesc = scrapy.field()
    movierate = scrapy.field()
    peoplecount = scrapy.field()
    moviedate = scrapy.field()
    moviecountry = scrapy.field()
    moviecategory = scrapy.field()
    moviepost = scrapy.field()
import json

class doubanpipeline(object):
    def __init__(self):
        self.f = open("douban.json","w",encoding='utf-8')

    def process_item(self, item, spider):
        content = json.dumps(dict(item),ensure_ascii = false)+"\n"
        self.f.write(content)
        return item

    def close_spider(self,spider):
        self.f.close()

 

这里xpath使用过程中,安利一个chrome插件xpathhelper。

    allowed_domains = ['douban.com']
    baseurl = "https://movie.douban.com/top250?start="
    offset = 0
    start_urls = [baseurl + str(offset)]


    def parse(self, response):
        node_list = response.xpath("//div[@class='item']")

        for node in node_list:
            item = doubanitem()
            item['moviename'] = node.xpath("./div[@class='info']/div[1]/a/span/text()").extract()[0]
            item['movierank'] = node.xpath("./div[@class='pic']/em/text()").extract()[0]
            item['director'] = node.xpath("./div[@class='info']/div[@class='bd']/p[1]/text()[1]").extract()[0]
            if len(node.xpath("./div[@class='info']/div[@class='bd']/p[@class='quote']/span[@class='inq']/text()")):
                item['moviedesc'] = node.xpath("./div[@class='info']/div[@class='bd']/p[@class='quote']/span[@class='inq']/text()").extract()[0]
            else:
                item['moviedesc'] = ""
            
            item['movierate'] = node.xpath("./div[@class='info']/div[@class='bd']/div[@class='star']/span[@class='rating_num']/text()").extract()[0] 
            item['peoplecount'] = node.xpath("./div[@class='info']/div[@class='bd']/div[@class='star']/span[4]/text()").extract()[0]
            item['moviedate'] = node.xpath("./div[2]/div[2]/p[1]/text()[2]").extract()[0].lstrip().split('\xa0/\xa0')[0]
            item['moviecountry'] = node.xpath("./div[2]/div[2]/p[1]/text()[2]").extract()[0].lstrip().split('\xa0/\xa0')[1]
            item['moviecategory'] = node.xpath("./div[2]/div[2]/p[1]/text()[2]").extract()[0].lstrip().split('\xa0/\xa0')[2]           
            item['moviepost'] = node.xpath("./div[@class='pic']/a/img/@src").extract()[0]
            yield item

        if self.offset <250:
            self.offset += 25
            url = self.baseurl+str(self.offset)
            yield scrapy.request(url,callback = self.parse)
     

 

这里基本可以爬虫,产生需要的json文件。

接下来是可视化过程。

我们先梳理一下,我们掌握的数据情况。

douban = pd.read_json('douban.json',lines=true,encoding='utf-8')
douban.info()

 基本我们可以分析,电影国家产地,电影拍摄年份,电影类别以及一些导演在top250中影响力。

先做个简单了解,可以使用value_counts()函数。

douban = pd.read_json('douban.json',lines=true,encoding='utf-8')
df_country = douban['moviecountry'].copy()

for i in range(len(df_country)):
    item = df_country.iloc[i].strip()
    df_country.iloc[i] = item[0]
print(df_country.value_counts())

美国电影占半壁江山,122/250,可以反映好莱坞电影工业之强大。同样,日本电影和香港电影在中国也有着重要地位。令人意外是,中国大陆地区电影数量不是令人满意。豆瓣影迷对于国内电影还是非常挑剔的。

douban = pd.read_json('douban.json',lines=true,encoding='utf-8')
df_date = douban['moviedate'].copy()

for i in range(len(df_date)):
    item = df_date.iloc[i].strip()
    df_date.iloc[i] = item[2]
print(df_date.value_counts())    

2000年以来电影数目在70%以上,考虑10代才过去9年和打分滞后性,总体来说越新的电影越能得到受众喜爱。这可能和豆瓣top250选取机制有关,必须人数在一定数量以上。

douban = pd.read_json('douban.json',lines=true,encoding='utf-8')
df_cate = douban['moviecategory'].copy()

for i in range(len(df_cate)):
    item = df_cate.iloc[i].strip()
    df_cate.iloc[i] = item[0]
print(df_cate.value_counts())    

剧情电影情节起伏更容易得到观众认可。

下面展示几张可视化图片

 

 

 

 不太会用python进行展示,有些难看。其实,推荐用echarts等插件,或者用excel,bi软件来处理图片,比较方便和美观。

第一次做这种爬虫和可视化,多有不足之处,恳请指出。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网