python使用BeautifulSoup與正則表達式爬取時光網(wǎng)不同地區(qū)top100電影并對比
前言
還有一年多就要畢業(yè)了,不準備考研的我要著手準備找實習及工作了,所以一直沒有更新。
因為Python是自學不久,發(fā)現(xiàn)很久不用的話以前學過的很多方法就忘了,今天打算使用簡單的BeautifulSoup和一點正則表達式的方法來爬一下top100電影,當然,我們并不僅是使用爬蟲爬取數(shù)據(jù),這樣的話,數(shù)據(jù)中存在很多的對人有用的信息則被忽略了。所以,爬取數(shù)據(jù)只是開頭,對這些數(shù)據(jù)根據(jù)意愿進行分析,或許能有額外的收獲。
注:本人還是Python菜鳥,若有錯誤歡迎指正
本次我們爬取時光網(wǎng)(http://www.mtime.com/top/movie/top100/)上的電影排名,該網(wǎng)站網(wǎng)頁結(jié)構(gòu)較簡單,爬取方便。
步驟:
1.爬取時光網(wǎng)top100電影,華語top100電影,日本top100電影,韓國top100電影的排名情況,電影名字,電影簡介,評分及評價人數(shù)
2. 將爬取數(shù)據(jù)保存為csv格式后,取出并使用matplotlib繪圖庫分析對比評論人數(shù)一項
3.將結(jié)果圖像保存
步驟一:爬取

由上圖可知電影信息在 li 節(jié)點內(nèi),而且發(fā)現(xiàn)第一頁與后面網(wǎng)頁地址不同,需要進行判斷。
第一頁地址為:http://www.mtime.com/top/movie/top100/
第二頁地址為:http://www.mtime.com/top/movie/top100/index-2.html
第三頁及后面地址均與第二頁相似,僅網(wǎng)址的數(shù)字相應增加,所以更改數(shù)字即可爬取
import requests
from bs4 import BeautifulSoup
import re
import csv
#定義爬取函數(shù)
def get_infos(htmls, csvname):
#信息頭
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
#flag在寫入文件時判斷是否為首行
flag = True
#判斷第一頁網(wǎng)址,第二頁及其后的網(wǎng)址
for i in range(10):
if i == 0:
html = htmls
else:
html = htmls + 'index-{}.html'.format(str(i+1))
res = requests.get(html, headers=headers)
soup = BeautifulSoup(res.text, 'lxml')
alls = soup.select('#asyncRatingRegion > li') #選取網(wǎng)頁的li節(jié)點的內(nèi)容
#對節(jié)點內(nèi)容進行循環(huán)遍歷
for one in alls:
paiming = one.div.em.string #排名
names = str(one.select('div.mov_pic > a')) #電影名稱并將列表字符串化
name = re.findall('.*?title="(.*?)">.*?', names, re.S)[0] #使用正則表達式提取內(nèi)容
content = str(one.select('div.mov_con > p.mt3')) #評論
realcontent = re.findall('.*?mt3">(.*?)</p>', content, re.S)[0] #同上
p1 = one.find(name='span', attrs={'class': 'total'}, text=re.compile('\d')) #評分在兩個節(jié)點,
p2 = one.find(name='span', attrs={'class': 'total2'}, text=re.compile('.\d'))
#判斷評分是否為空
if p1 and p2 != None:
p1 = p1.string
p2 = p2.string
else:
p1 = 'no'
p2 = ' point'
point = p1 + p2 + '分'
numbers = one.find(text=re.compile('評分')) #評分數(shù)量
# 保存為csv
csvnames = 'C:\\Users\lenovo\Desktop\\' + csvname + '.csv'
with open(csvnames, 'a+', encoding='utf-8') as f:
writer = csv.writer(f)
if flag:
writer.writerow(('paiming', 'name', 'realcontent', 'point', 'numbers'))
writer.writerow((paiming, name, realcontent, point, numbers))
flag = False
#調(diào)用函數(shù)
Japan_html = 'http://www.mtime.com/top/movie/top100_japan/'
csvname1 = 'Japan_top'
get_infos(Japan_html, csvname1)
Korea_html = 'http://www.mtime.com/top/movie/top100_south_korea/'
csvname2 = 'Korea_top'
get_infos(Korea_html, csvname2)
這里要注意的是要有些電影沒有評分,為了預防出現(xiàn)這種情況,所以要進行判斷
注:上述沒有添加華語電影top100及所有電影top100的代碼,可自行添加。
爬取結(jié)果部分內(nèi)容如下:

-----------------------------------------------------------------------------------------------------------------------------------------------------------------
步驟二和三:導入數(shù)據(jù)并使用matplotlib分析,保存分析圖片
import csv
from matplotlib import pyplot as plt
#中文亂碼處理
plt.rcParams['font.sans-serif'] =['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
def read_csv(csvname):
csvfile_name = 'C:\\Users\lenovo\Desktop\\' + csvname + '.csv'
#打開文件并存入列表
with open(csvfile_name,encoding='utf-8') as f:
reader = csv.reader(f)
header_row = next(reader)
name = []
for row in reader:
name.append(row)
#取列表中非空元素
real = []
for i in name:
if len(i) != 0:
real.append(i)
#去除中文并將數(shù)據(jù)轉(zhuǎn)換為整形
t = 0
ss = []
for j in real:
ss.append(int(real[t][4][:-5]))
t += 1
return ss
#繪制對比圖形
All_plt = read_csv('bs1') #調(diào)用函數(shù)
China_plt = read_csv('China_top')
Japan_plt = read_csv('Japan_top')
Korea_plt = read_csv('Korea_top')
shu = list(range(1,101))
fig = plt.figure(dpi=128, figsize=(10, 6)) #設置圖形界面
plt.subplot(2,1,1)
plt.bar(shu ,All_plt, align='center', color='green', label='World', alpha=0.6) #繪制條圖形,align指定橫坐標在中心,顏色,alpha指定透明度
plt.bar(shu ,China_plt, color='indigo', label='China', alpha=0.4) #繪制圖形,顏色, label屬性用于后面使用legend方法時顯示圖例標簽
plt.bar(shu ,Japan_plt, color='blue', label='Japan',alpha=0.5) #繪制圖形,顏色,
plt.bar(shu ,Korea_plt, color='yellow', label='Korea',alpha=0.5) #繪制圖形,顏色,
plt.ylabel('評論數(shù)', fontsize=10) #縱坐標題目,字體大小
plt.title('不同地區(qū)的電影top100對比', fontsize=10) #圖形標題
plt.legend(loc='best')
plt.subplot(2,1,2)
plt.plot(shu , All_plt, linewidth=1, c='green', label='World') #繪制圖形,指定線寬,顏色,label屬性用于后面使用legend方法時顯示圖例標簽
plt.plot(shu ,China_plt, linewidth=1, c='indigo', label='China', ls='-.') #繪制圖形,指定線寬,顏色,
plt.plot(shu ,Japan_plt, linewidth=1, c='green', label='Japan', ls='--') #繪制圖形,指定線寬,顏色,
plt.plot(shu ,Korea_plt, linewidth=1, c='red', label='Korea', ls=':') #繪制圖形,指定線寬,顏色,
plt.ylabel('comments', fontsize=10) #縱坐標題目,字體大小
plt.title('The different top 100 movies\'comments comparison', fontsize=10) #圖形標題
plt.legend(loc='best')
'''
plt.legend()——loc參數(shù)選擇
'best' : 0, #自動選擇最好位置
'upper right' : 1,
'upper left' : 2,
'lower left' : 3,
'lower right' : 4,
'right' : 5,
'center left' : 6,
'center right' : 7,
'lower center' : 8,
'upper center' : 9,
'center' : 10,
'''
plt.savefig('C:\\Users\lenovo\Desktop\\bs1.png') #保存圖片
plt.show() #顯示圖形
這里需要注意的是讀取保存的csv文件并將數(shù)據(jù)傳入列表時,每一個電影數(shù)據(jù)又是一個列表(先稱為有效列表),每個有效列表前后都有一個空列表,所以需要將空列表刪除,才能進行下一步
評分數(shù)據(jù)為string類型且有中文,所以進行遍歷將中文去除并轉(zhuǎn)換為int。
最后保存的對比分析圖片:

本次使用的爬取方法、爬取內(nèi)容、分析內(nèi)容都很容易,但我在完成過程中,發(fā)現(xiàn)自己還是會出現(xiàn)各種各樣的問題,說明還有很多需要改善進步的地方。
同時歡迎大家指正。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關(guān)文章
python抓取網(wǎng)頁時字符集轉(zhuǎn)換問題處理方案分享
python學習過程中發(fā)現(xiàn)英文不好學起來挺困難的,其中小弟就遇到一個十分蛋疼的問題,百度了半天就沒找到解決辦法~囧~摸索了半天自己解決了,記錄下來與君共勉。2014-06-06
python 創(chuàng)建一個保留重復值的列表的補碼
這篇文章主要介紹了python 創(chuàng)建一個保留重復值的列表的補碼的相關(guān)資料,需要的朋友可以參考下2018-10-10

