这几天朋友圈,微博都被《哪吒之魔童降世》这部电影刷屏了,有人说它是“国漫之光”,上映4天,票房已经突破9亿了。口碑上,影片自点映开分以来,口碑连续十天稳居所有在映影片榜首之位,收获无数观众喜爱与支持。这部电影是不是真的如网友们所说呢?事实还是要靠数据来说话,接下来将用Python爬取豆瓣上的影评,分析影评给出一个准确答案。
爬虫分为:爬取网页,分析网页,存储数据,分析数据这四步。我将一步一步演示。
第一步,爬取单页的豆瓣网《哪吒之魔童降世》短评的页面:要传递headers,豆瓣是有反爬虫措施的,如果不传递headers,它是不让我们爬的。Headers里有Cookie,Referer,user-agent,Cookie维持当前的访问对话,Referer标识请求来源的页面,user-agent可以将爬虫伪装成浏览器,然后传入url即可。
def get_page(url):
headers = {
'Referer':'https://movie.douban.com/subject/26794435/reviews?start=60',
'Cookie':'bid=DxHhSB_-Zes; ll="118230"; __yadk_uid=H4SrCzj2ByHOg7fX30crzR3NU4YkFTkW; _vwo_uuid_v2=D63BD3ECABD38BCB6F51C5168C4F56A53|92b1e241a5634c49f107ed6246293470; __gads=ID=d52de5866790ac5c:T=1563240246:S=ALNI_MZq6g6AMWrsRhzMI17NTHSXoo2c_g; trc_cookie_storage=taboola%2520global%253Auser-id%3D55735cb5-56c7-45cd-834d-f50a9d37cb97-tuct425fa8a; gr_user_id=8e2a15f1-e815-4d60-89a3-327e94ef029f; viewed="33442264"; push_noty_num=0; push_doumail_num=0; __utmv=30149280.18138; __utmc=30149280; __utmc=223695111; ps=y; ap_v=0,6.0; __utma=30149280.570724812.1563160554.1564395173.1564403664.19; __utmb=30149280.0.10.1564403664; __utmz=30149280.1564403664.19.12.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utma=223695111.985218115.1563160554.1564387882.1564403664.17; __utmb=223695111.0.10.1564403664; __utmz=223695111.1564403664.17.11.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1564403664%2C%22https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DZY44JoMA5t-V1-xpReFdXSZYMuJmYaaIXjgPkPgX8Xari5rfXaYZ6F01rE1bUUmL%26wd%3D%26eqid%3Dd36d559c000bc439000000025d3ee7cb%22%5D; _pk_ses.100001.4cf6=*; dbcl2="181384057:8I818hPqXwg"; ck=YL4Y; _pk_id.100001.4cf6=6f5f12305430b1f3.1563160554.16.1564405190.1564388517.',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}
try:
r = requests.get(url,headers=headers)
if r.status_code == 200:
return r.content
return None
except RequestException:
return None
第二步分析网页:这里小编用比较常用的解析库BeautifulSoup来解析网页,当然也可以用XPath,pyquery解析库来解析。解析网页的过程,只需要知道要爬取的数据在那个节点下即可,然后获取属性或者文本。废话不多说,直接上代码。
def parse_page(html):
soup = BeautifulSoup(html.decode('utf-8'),'lxml')
all_comments = soup.find('div',class_='mod-bd')
#print(all_comments)
for each_comment in all_comments.find_all('div',class_='comment'):
authors = each_comment.find('a',class_="")
author = authors.text
#scores = each_comment.find('span',class_="rating")
#score = scores['title']
all_span_tag = each_comment.find_all('span')
score = all_span_tag[4]['title']
comment_times = each_comment.find('span', class_="comment-time")
comment_time = comment_times.text
comments = each_comment.find('span', class_="short")
comment = comments.text
第三步存储数据:文本存储,数据库,向数据库插入数据,要用字典的形式,下面代码分别保存在文本文档里和MongoDB数据库中。
neirong = '作者:{},评分:{},评分时间:{},影评:{}'.format(author.strip(), score.strip(), comment_time.strip(), comment.strip())
with open('哪吒之魔童降世.txt','a',encoding='gb18030') as file:
file.write(neirong)
text = {
'作者': author.strip(),
'评分': score.strip(),
'评分时间': comment_time.strip(),
'影评': comment.strip(),
}
save_to_mongo(text)
client = MongoClient()
db = client.Text
collection = db.comment
def save_to_mongo(result):
try:
if collection.insert_one(result):
print('存储成功')
except Exception:
print("存储失败")
PS:上面是爬取一页的影评,因为要爬取所有的影评,所以需要分页爬取,通过切换页面可以发现,控制页面切换参数是start,只要设置不同的start值就可以爬取所有的影评了,遍历一下就行。
def main(offest):
url = "https://movie.douban.com/subject/26794435/comments?start="+str(offest)
html = get_page(url)
parse_page(html)
if __name__ == '__main__':
for i in range(0, 25):
print("正在爬取第", i, "页影评")
time.sleep(1)
main(i * 20)
第四步分析数据,这里做一个影评的词云,以及满意度的饼图。从文本读取爬取的数据,生成词云。
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import jieba
#读取文本
text = open('哪吒之魔童降世.txt',encoding='gb18030').read()
#分词
text = ''.join(jieba.cut(text))
#mask
mask = np.array(Image.open('哪吒.jpg'))
#数据清洗
stopwords = ['评分','评分时间','影评','作者']
#生成词云
wc = WordCloud(mask=mask,stopwords=stopwords).generate(text)
#颜色
color = ImageColorGenerator(mask)
wc.recolor(color_func=color)
#显示词云
plt.imshow(wc)
plt.axis('off')
plt.show()
#保存图片
wc.to_file('魔童降世.jpg')
对于生成饼图的过程我就不多说了,因为我刚接触爬虫,对一些知识点还很模糊,就直接上代码了。
from pymongo import MongoClient
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
index = ['力荐','推荐','还行','较差','很差']
client = MongoClient('mongodb://127.0.0.1:27017/')
db = client.Text
comment = db.comment
value = []
for i in index:
num = comment.count_documents({'评分':i})
value.append(num)
print(value)
plt.bar(x=index,height=value,color='red',width=0.5)
#plt.pie(x=value,labels=index, autopct='%.0d%%')
#plt.title('满意度')
plt.show()
大家感兴趣的话,可以关注我的公众号,刚开始做,记录自己学习爬虫的一些经验。