
前言
如果大家经常阅读Python爬虫相关的公众号,都会是以爬虫+数据分析的形式展现的,这样很有趣,图表也很不错,今天了,我就来分享上一次在培训中的一个作品:猫眼电影爬虫及分析。
通过猫眼电影TOP100榜的爬虫,然后进行可视化,让学员体会到,小数据爬虫也能玩出这样的花样来。
爬虫
爬虫分析
这里是获取的是top100的电影数据,进行了跨页爬虫,获取的字段:电影名,主演,上映时间,评分,电影类型和时长。最后保存在csv文件中。
爬虫代码
import requests
from lxml import etree
import csv
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
def get_url(url):
res = requests.get(url,headers=headers)
html = etree.HTML(res.text)
infos = html.xpath('//dl[@class="board-wrapper"]/dd')
for info in infos:
name = info.xpath('div/div/div[1]/p[1]/a/text()')[0]
info_url = 'http://maoyan.com' + info.xpath('div/div/div[1]/p[1]/a/@href')[0]
star = info.xpath('div/div/div[1]/p[2]/text()')[0].strip()
release_time = info.xpath('div/div/div[1]/p[3]/text()')[0].strip()
score_1 = info.xpath('div/div/div[2]/p/i[1]/text()')[0]
score_2 = info.xpath('div/div/div[2]/p/i[2]/text()')[0]
score = score_1 + score_2
# print(name,star,release_time,score,info_url)
get_info(info_url,name,star,release_time,score)
def get_info(url,name,star,time,score):
res = requests.get(url, headers=headers)
html = etree.HTML(res.text)
style = html.xpath('/html/body/div[3]/div/div[2]/div[1]/ul/li[1]/text()')[0]
long_time = html.xpath('/html/body/div[3]/div/div[2]/div[1]/ul/li[2]/text()')[0].split('/')[1].strip()
print(name,star,time,score,style,long_time)
writer.writerow([name,star,time,score,style,long_time])
if __name__ == '__main__':
fp = open('maoyan_2.csv','w',encoding='utf-8',newline='')
writer = csv.writer(fp)
writer.writerow(['name','star','time','score','style','long_time'])
urls = ['http://maoyan.com/board/4?offset={}'.format(str(i)) for i in range(0, 100, 10)]
for url in urls:
get_url(url)

数据分析
数据分析我做成了PPT的样子,大家可以看看~
总体情况
100部电影,平均得分9.0,平均电影时长128.63。

电影年份趋势
电影年份趋势不大,规律不太明显。

电影月份
大家看电影都知道,电影基本在假期上映更有热度,这里统计出来,发现下半年的电影比上半年电影好很多~

地区
中国和美国还是占了很多的,韩国和日本电影也很不错~

电影类型
电影大部分都是剧情的,爱情才是真谛啊。

演员
小哥和星爷承载了我们的清楚呀~

总结
别看这小小的100条数据,是不是也可以玩出不一样的花样来。关注公众号:罗罗攀,回复(猫眼电影),即可获取爬虫+数据分析代码。