日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python爬虫以及数据可视化分析!

發(fā)布時間:2024/1/8 python 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python爬虫以及数据可视化分析! 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

簡單幾步,通過Python對B站番劇排行數(shù)據(jù)進(jìn)行爬取,并進(jìn)行可視化分析

源碼文件可以參考Github上傳的項目:https://github.com/Lemon-Sheep/Py/tree/master

下面,我們開始吧!

PS: 作為Python爬蟲初學(xué)者,如有不正確的地方,望各路大神不吝賜教[抱拳]

本項目將會對B站番劇排行的數(shù)據(jù)進(jìn)行網(wǎng)頁信息爬取以及數(shù)據(jù)可視化分析

?

首先,準(zhǔn)備好相關(guān)庫

requests、pandas、BeautifulSoup、matplotlib等

因為這是第三方庫,所以我們需要額外下載 下載有兩種方法(以requests為例,其余庫的安裝方法類似):

(一)在命令行輸入

前提:裝了pip( Python 包管理工具,提供了對Python 包的查找、下載、安裝、卸載的功能。 )

pip install requests

(二)通過PyCharm下載

第一步:編譯器左上角File–>Settings…

第二步:找到Project Interpreter 點(diǎn)擊右上角加號按鈕,彈出界面上方搜索庫名:requests,點(diǎn)擊左下角Install ,當(dāng)提示successfully時,即安裝完成。

?

?

?

準(zhǔn)備工作做好后,開始項目的實行

一、獲取網(wǎng)頁內(nèi)容

def get_html(url):try:r = requests.get(url) # 使用get來獲取網(wǎng)頁數(shù)據(jù)r.raise_for_status() # 如果返回參數(shù)不為200,拋出異常r.encoding = r.apparent_encoding # 獲取網(wǎng)頁編碼方式return r.text # 返回獲取的內(nèi)容except:return '錯誤'

我們來看爬取情況,是否有我們想要的內(nèi)容:

def main():url = 'https://www.bilibili.com/v/popular/rank/bangumi' # 網(wǎng)址html = get_html(url) # 獲取返回值print(html) # 打印if __name__ == '__main__': #入口main()

爬取結(jié)果如下圖所示:

成功!

二、信息解析階段:

第一步,先構(gòu)建BeautifulSoup實例

soup = BeautifulSoup(html, 'html.parser') # 指定BeautifulSoup的解析器

第二步,初始化要存入信息的容器

# 定義好相關(guān)列表準(zhǔn)備存儲相關(guān)信息TScore = [] # 綜合評分name = [] # 動漫名字play= [] # 播放量review = [] # 評論數(shù)favorite= [] # 收藏數(shù)

第三步,開始信息整理 我們先獲取番劇的名字,并將它們先存進(jìn)列表中

# ******************************************** 動漫名字存儲for tag in soup.find_all('div', class_='info'):# print(tag)bf = tag.a.stringname.append(str(bf))print(name)

此處我們用到了beautifulsoup的find_all()來進(jìn)行解析。在這里,find_all()的第一個參數(shù)是標(biāo)簽名,第二個是標(biāo)簽中的class值(注意下劃線哦(class_=‘info’))。

我們在網(wǎng)頁界面按下F12,就能看到網(wǎng)頁代碼,找到相應(yīng)位置,就能清晰地看見相關(guān)信息:

?

接著,我們用幾乎相同的方法來對綜合評分、播放量,評論數(shù)和收藏數(shù)來進(jìn)行提取

# ******************************************** 播放量存儲for tag in soup.find_all('div', class_='detail'):# print(tag)bf = tag.find('span', class_='data-box').get_text()# 統(tǒng)一單位為‘萬’if '億' in bf:num = float(re.search(r'\d(.\d)?', bf).group()) * 10000# print(num)bf = numelse:bf = re.search(r'\d*(\.)?\d', bf).group()play.append(float(bf))print(play)# ******************************************** 評論數(shù)存儲for tag in soup.find_all('div', class_='detail'):# pl = tag.span.next_sibling.next_siblingpl = tag.find('span', class_='data-box').next_sibling.next_sibling.get_text()# *********統(tǒng)一單位if '萬' not in pl:pl = '%.1f' % (float(pl) / 10000)# print(123, pl)else:pl = re.search(r'\d*(\.)?\d', pl).group()review.append(float(pl))print(review)# ******************************************** 收藏數(shù)for tag in soup.find_all('div', class_='detail'):sc = tag.find('span', class_='data-box').next_sibling.next_sibling.next_sibling.next_sibling.get_text()sc = re.search(r'\d*(\.)?\d', sc).group()favorite.append(float(sc))print(favorite)# ******************************************** 綜合評分for tag in soup.find_all('div', class_='pts'):zh = tag.find('div').get_text()TScore.append(int(zh))print('綜合評分', TScore)

其中有個.next_sibling是用于提取同級別的相同標(biāo)簽信息,如若沒有這個方法,當(dāng)它找到第一個’span’標(biāo)簽之后,就不會繼續(xù)找下去了(根據(jù)具體情況來疊加使用此方法); 還用到了正則表達(dá)式來提取信息(需要導(dǎo)入庫‘re’)

最后我們將提取的信息,存進(jìn)excel表格之中,并返回結(jié)果集

# 存儲至excel表格中info = {'動漫名': name, '播放量(萬)': play, '評論數(shù)(萬)': review,'收藏數(shù)(萬)': favorite, '綜合評分': TScore}dm_file = pandas.DataFrame(info)dm_file.to_excel('Dongman.xlsx', sheet_name="動漫數(shù)據(jù)分析")# 將所有列表返回return name, play, review, favorite, TScore

我們可以打開文件看一看存儲的信息格式(雙擊打開)

成功!

三、數(shù)據(jù)可視化分析

我們先做一些基礎(chǔ)設(shè)置 要先準(zhǔn)備一個文件: STHeiti Medium.ttc [注意存放在項目中的位置]

?

my_font = font_manager.FontProperties(fname='./data/STHeiti Medium.ttc') # 設(shè)置中文字體(圖表中能顯示中文)# 為了坐標(biāo)軸上能顯示中文plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falsedm_name = info[0] # 番劇名dm_play = info[1] # 番劇播放量dm_review = info[2] # 番劇評論數(shù)dm_favorite = info[3] # 番劇收藏數(shù)dm_com_score = info[4] # 番劇綜合評分# print(dm_com_score)

然后,開始使用matplot來繪制圖形,實現(xiàn)數(shù)據(jù)可視化分析 文中有詳細(xì)注釋,這里就不再贅述了,聰明的你一定一看就懂了~

# **********************************************************************綜合評分和播放量對比# *******綜合評分條形圖fig, ax1 = plt.subplots()plt.bar(dm_name, dm_com_score, color='red') #設(shè)置柱狀圖plt.title('綜合評分和播放量數(shù)據(jù)分析', fontproperties=my_font) # 表標(biāo)題ax1.tick_params(labelsize=6) plt.xlabel('番劇名') # 橫軸名plt.ylabel('綜合評分') # 縱軸名plt.xticks(rotation=90, color='green') # 設(shè)置橫坐標(biāo)變量名旋轉(zhuǎn)度數(shù)和顏色# *******播放量折線圖ax2 = ax1.twinx() # 組合圖必須加這個ax2.plot(dm_play, color='cyan') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('播放量') # y軸plt.plot(1, label='綜合評分', color="red", linewidth=5.0) # 圖例plt.plot(1, label='播放量', color="cyan", linewidth=1.0, linestyle="-") # 圖例plt.legend()plt.savefig(r'E:1.png', dpi=1000, bbox_inches='tight') #保存至本地plt.show()

來看看效果

有沒有瞬間就感覺高~大~上~~了(嘿嘿~)

然后我們用相同的方法來多繪制幾個對比圖:

# **********************************************************************評論數(shù)和收藏數(shù)對比# ********評論數(shù)條形圖fig, ax3 = plt.subplots()plt.bar(dm_name, dm_review, color='green')plt.title('番劇評論數(shù)和收藏數(shù)分析')plt.ylabel('評論數(shù)(萬)')ax3.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******收藏數(shù)折線圖ax4 = ax3.twinx() # 組合圖必須加這個ax4.plot(dm_favorite, color='yellow') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('收藏數(shù)(萬)')plt.plot(1, label='評論數(shù)', color="green", linewidth=5.0)plt.plot(1, label='收藏數(shù)', color="yellow", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:2.png', dpi=1000, bbox_inches='tight')# **********************************************************************綜合評分和收藏數(shù)對比# *******綜合評分條形圖fig, ax5 = plt.subplots()plt.bar(dm_name, dm_com_score, color='red')plt.title('綜合評分和收藏數(shù)量數(shù)據(jù)分析')plt.ylabel('綜合評分')ax5.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******收藏折線圖ax6 = ax5.twinx() # 組合圖必須加這個ax6.plot(dm_favorite, color='yellow') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('收藏數(shù)(萬)')plt.plot(1, label='綜合評分', color="red", linewidth=5.0)plt.plot(1, label='收藏數(shù)', color="yellow", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:3.png', dpi=1000, bbox_inches='tight')# **********************************************************************播放量和評論數(shù)對比# *******播放量條形圖fig, ax7 = plt.subplots()plt.bar(dm_name, dm_play, color='cyan')plt.title('播放量和評論數(shù) 數(shù)據(jù)分析')plt.ylabel('播放量(萬)')ax7.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******評論數(shù)折線圖ax8 = ax7.twinx() # 組合圖必須加這個ax8.plot(dm_review, color='green') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('評論數(shù)(萬)')plt.plot(1, label='播放量', color="cyan", linewidth=5.0)plt.plot(1, label='評論數(shù)', color="green", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:4.png', dpi=1000, bbox_inches='tight')plt.show()

我們來看看最終效果

?

Nice!很完美~ 大家可以根據(jù)自己的想法按照相同的方法進(jìn)行數(shù)據(jù)組合分析。

最后,附上全部代碼

import re import pandas import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt from matplotlib import font_managerdef get_html(url):try:r = requests.get(url) # 使用get來獲取網(wǎng)頁數(shù)據(jù)r.raise_for_status() # 如果返回參數(shù)不為200,拋出異常r.encoding = r.apparent_encoding # 獲取網(wǎng)頁編碼方式return r.text # 返回獲取的內(nèi)容except:return '錯誤'def save(html):# 解析網(wǎng)頁soup = BeautifulSoup(html, 'html.parser') # 指定Beautiful的解析器為“html.parser”with open('./data/B_data.txt', 'r+', encoding='UTF-8') as f:f.write(soup.text)# 定義好相關(guān)列表準(zhǔn)備存儲相關(guān)信息TScore = [] # 綜合評分name = [] # 動漫名字bfl = [] # 播放量pls = [] # 評論數(shù)scs = [] # 收藏數(shù)# ******************************************** 動漫名字存儲for tag in soup.find_all('div', class_='info'):# print(tag)bf = tag.a.stringname.append(str(bf))print(name)# ******************************************** 播放量存儲for tag in soup.find_all('div', class_='detail'):# print(tag)bf = tag.find('span', class_='data-box').get_text()# 統(tǒng)一單位為‘萬’if '億' in bf:num = float(re.search(r'\d(.\d)?', bf).group()) * 10000# print(num)bf = numelse:bf = re.search(r'\d*(\.)?\d', bf).group()bfl.append(float(bf))print(bfl)# ******************************************** 評論數(shù)存儲for tag in soup.find_all('div', class_='detail'):# pl = tag.span.next_sibling.next_siblingpl = tag.find('span', class_='data-box').next_sibling.next_sibling.get_text()# *********統(tǒng)一單位if '萬' not in pl:pl = '%.1f' % (float(pl) / 10000)# print(123, pl)else:pl = re.search(r'\d*(\.)?\d', pl).group()pls.append(float(pl))print(pls)# ******************************************** 收藏數(shù)for tag in soup.find_all('div', class_='detail'):sc = tag.find('span', class_='data-box').next_sibling.next_sibling.next_sibling.next_sibling.get_text()sc = re.search(r'\d*(\.)?\d', sc).group()scs.append(float(sc))print(scs)# ******************************************** 綜合評分for tag in soup.find_all('div', class_='pts'):zh = tag.find('div').get_text()TScore.append(int(zh))print('綜合評分', TScore)# 存儲至excel表格中info = {'動漫名': name, '播放量(萬)': bfl, '評論數(shù)(萬)': pls, '收藏數(shù)(萬)': scs, '綜合評分': TScore}dm_file = pandas.DataFrame(info)dm_file.to_excel('Dongman.xlsx', sheet_name="動漫數(shù)據(jù)分析")# 將所有列表返回return name, bfl, pls, scs, TScoredef view(info):my_font = font_manager.FontProperties(fname='./data/STHeiti Medium.ttc') # 設(shè)置中文字體(圖標(biāo)中能顯示中文)dm_name = info[0] # 番劇名dm_play = info[1] # 番劇播放量dm_review = info[2] # 番劇評論數(shù)dm_favorite = info[3] # 番劇收藏數(shù)dm_com_score = info[4] # 番劇綜合評分# print(dm_com_score)# 為了坐標(biāo)軸上能顯示中文plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = False# **********************************************************************綜合評分和播放量對比# *******綜合評分條形圖fig, ax1 = plt.subplots()plt.bar(dm_name, dm_com_score, color='red') #設(shè)置柱狀圖plt.title('綜合評分和播放量數(shù)據(jù)分析', fontproperties=my_font) # 表標(biāo)題ax1.tick_params(labelsize=6)plt.xlabel('番劇名') # 橫軸名plt.ylabel('綜合評分') # 縱軸名plt.xticks(rotation=90, color='green') # 設(shè)置橫坐標(biāo)變量名旋轉(zhuǎn)度數(shù)和顏色# *******播放量折線圖ax2 = ax1.twinx() # 組合圖必須加這個ax2.plot(dm_play, color='cyan') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('播放量') # y軸plt.plot(1, label='綜合評分', color="red", linewidth=5.0) # 圖例plt.plot(1, label='播放量', color="cyan", linewidth=1.0, linestyle="-") # 圖例plt.legend()plt.savefig(r'E:1.png', dpi=1000, bbox_inches='tight') #保存至本地# plt.show()# **********************************************************************評論數(shù)和收藏數(shù)對比# ********評論數(shù)條形圖fig, ax3 = plt.subplots()plt.bar(dm_name, dm_review, color='green')plt.title('番劇評論數(shù)和收藏數(shù)分析')plt.ylabel('評論數(shù)(萬)')ax3.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******收藏數(shù)折線圖ax4 = ax3.twinx() # 組合圖必須加這個ax4.plot(dm_favorite, color='yellow') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('收藏數(shù)(萬)')plt.plot(1, label='評論數(shù)', color="green", linewidth=5.0)plt.plot(1, label='收藏數(shù)', color="yellow", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:2.png', dpi=1000, bbox_inches='tight')# **********************************************************************綜合評分和收藏數(shù)對比# *******綜合評分條形圖fig, ax5 = plt.subplots()plt.bar(dm_name, dm_com_score, color='red')plt.title('綜合評分和收藏數(shù)量數(shù)據(jù)分析')plt.ylabel('綜合評分')ax5.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******收藏折線圖ax6 = ax5.twinx() # 組合圖必須加這個ax6.plot(dm_favorite, color='yellow') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('收藏數(shù)(萬)')plt.plot(1, label='綜合評分', color="red", linewidth=5.0)plt.plot(1, label='收藏數(shù)', color="yellow", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:3.png', dpi=1000, bbox_inches='tight')# **********************************************************************播放量和評論數(shù)對比# *******播放量條形圖fig, ax7 = plt.subplots()plt.bar(dm_name, dm_play, color='cyan')plt.title('播放量和評論數(shù) 數(shù)據(jù)分析')plt.ylabel('播放量(萬)')ax7.tick_params(labelsize=6)plt.xticks(rotation=90, color='green')# *******評論數(shù)折線圖ax8 = ax7.twinx() # 組合圖必須加這個ax8.plot(dm_review, color='green') # 設(shè)置線粗細(xì),節(jié)點(diǎn)樣式plt.ylabel('評論數(shù)(萬)')plt.plot(1, label='播放量', color="cyan", linewidth=5.0)plt.plot(1, label='評論數(shù)', color="green", linewidth=1.0, linestyle="-")plt.legend()plt.savefig(r'E:4.png', dpi=1000, bbox_inches='tight')plt.show()def main():url = 'https://www.bilibili.com/v/popular/rank/bangumi' # 網(wǎng)址html = get_html(url) # 獲取返回值# print(html)info = save(html)view(info)if __name__ == '__main__':main()

關(guān)于圖表的分析和得出的結(jié)論,這里就不描述了,一千個讀者就有一千個哈姆雷特,每個人有每個人的分析描述方法,相信你們能有更加透徹的見解分析。

以上就是關(guān)于爬蟲以及數(shù)據(jù)可視化分析的內(nèi)容,希望能幫到你們! 源碼點(diǎn)擊藍(lán)色字體:后記

近期有很多朋友通過私信咨詢有關(guān)Python學(xué)習(xí)問題。為便于交流,點(diǎn)擊藍(lán)色自己加入討論解答資源基地

喜歡記得點(diǎn)個贊哦~

?

總結(jié)

以上是生活随笔為你收集整理的Python爬虫以及数据可视化分析!的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。