爬取豆瓣網影評數據並進行簡單分析與展示


編譯在線環境:

https://www.kesci.com

一.  內容

1、使用Python爬蟲爬取豆瓣網某一部電影的評論信息;

2、從評論信息中統計各級星評的數量占比

 1 from urllib import request
 2 from bs4 import BeautifulSoup
 3 import matplotlib as mpl
 4 import matplotlib.pyplot as plt
 5 import pandas as pd
 6 import numpy as np
 7 import requests
 8 import re
 9 
10 """
11 生成分頁網址
12 n:需要生成的頁數
13 """
14 def get_urls(n):
15     urls=[]
16     for i in range(0,n):
17         u='https://movie.douban.com/subject/30166972/comments?start='+str(i*20)+'&limit=20&sort=new_score&status=P'
18         urls.append(u)
19     return urls
20 #get_urls(5)
21 
22 """
23 【從分頁采集數據】
24 u:輸入分頁網址
25 """
26 def get_informations(u):
27     headers = {
28         'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36'}
29     r = requests.get(u, headers=headers)
30     soup = BeautifulSoup(r.text, 'lxml')
31     ims = soup.find_all('div', class_='comment-item')
32 
33     # print(ims)
34     data = []
35 
36     for i in ims:
37         dic = {}
38         dic['用戶名'] = i.find('span', class_='comment-info').find('a', class_="").text
39         mystar = i.find('span', class_='comment-info').find('span').next_sibling.next_sibling
40         mystar = str(mystar)
41         t = re.findall(r'\d+', mystar)
42         dic['所評星級'] = str(t[0])
43         dic['評論'] = i.find('span', class_='short').text
44         dic['評論獲贊數'] = i.find('span', class_='votes').text
45         dic['評論時間'] = i.find('span', class_='comment-time').text.strip()
46         data.append(dic)
47     return data
48 #get_informations('https://movie.douban.com/subject/30166972/comments?start=0&limit=20&sort=new_score&status=P')
49 
50 """
51 【從每一頁采取所有數據】
52 n:需要采集的頁數
53 """
54 def get_alldata(n):
55     alldata = []
56     for u in get_urls(n):
57         alldata.extend(get_informations(u))
58     """
59     清洗數據
60     轉換數據類型以及星級去除%
61     .loc就是索引,逗號前面是行索引,逗號后面是列索引
62     """
63     df.loc[:, '所評星級'] = df['所評星級'].astype('float')
64     df.loc[:, '評論獲贊數'] = df['評論獲贊數'].astype('int')
65 
66     return pd.DataFrame(alldata)
67 
68 """
69 內容1、爬取豆瓣網某一部電影的評論信息
70 """
71 #保存數據到《少年的你》影評.csv
72 df = get_alldata(5)
73 df.to_csv('《少年的你》影評.csv',index=False,encoding='utf-8')
74 print(df)
75 
76 """pandas繪圖:直方圖,bins是像素"""
77 df['星級'].hist(bins=20)

二. 所涉及的知識點:

1.python去除空格和換行符的方法

#str.strip()
s1='\nabcdefg\n'
print(s1.strip())
 1 字符竄:DataFrame數據框里邊的name列為字符竄形式
 2 
 3 清除字符竄左側是空值:
 4 
 5 newname=df['name'].str.lstrip()
 6 
 7 
 8 刪除右側:
 9 newname=df['name'].str.rstrip()
10 
11 
12 刪除全部:
13 newname=df['name'].str.strip()

2.pandas常用函數

https://www.cnblogs.com/rexyan/p/7975707.html

https://www.jianshu.com/p/7332afd70797

3.Pandas 關於統計個數

https://blog.csdn.net/cyx441984694/article/details/85029009?utm_source=distribute.pc_relevant.none-task

4.幾個相同的標簽<>,如果想獲得第二個標簽里面的內容

next_sibling
“”“
<p class='comment-time'>ads<\p>
<p class='comment-time'>bdg<\p>
<p class='comment-time'>fgh<\p >
可以通過next_sibling
”“”
Tsecond =  i.find('p',class_='comment-time').next_sibling.next_sibling

TsecondText = i.find('p',class_='comment-time').next_sibling.next_sibling.text

5.matplotlib畫圖時的中文設置

 采用matplotlib作圖時默認設置下是無法顯示中文的,加上以下語句:

import matplotlib as mpl
import matplotlib.pyplot as plt

mpl.rcParams['font.sans-serif'] = ['KaiTi']
mpl.rcParams['font.serif'] = ['KaiTi']

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM