Python爬蟲之對CSDN榜單進行分析
前言
本篇文章的主要內(nèi)容是利用Python對CSDN熱榜變冷榜的指標數(shù)據(jù)進行分析的爬蟲
分析一下各指標
開始爬取熱榜,請稍候...
耗時:2.199401808s
【Top100指標統(tǒng)計】
瀏覽為0的: 3
評論為0的: 76
收藏為0的: 51
瀏覽評論0的: 3
三指標都0的: 2
瀏覽個位數(shù)的: 25
評論個位數(shù)的: 98
收藏個位數(shù)的: 86
無封面題圖的: 74
瀏覽>=100的: 18
評論>=10的: 1
收藏>=10的: 13
【Top50指標統(tǒng)計】
瀏覽為0的: 0
評論為0的: 36
收藏為0的: 22
瀏覽評論0的: 0
三指標都0的: 0
瀏覽個位數(shù)的: 15
評論個位數(shù)的: 49
收藏個位數(shù)的: 39
無封面題圖的: 38
瀏覽>=200的: 12
評論>=20的: 0
收藏>=20的: 8
開始爬取Top100網(wǎng)頁,請稍候(大約1分鐘)...
耗時:50.254692171s
下載失敗數(shù):0
【Top100博客等級分布】
等級 1: 11
等級 2: 12
等級 3: 22
等級 4: 20
等級 5: 21
等級 6: 3
等級 7: 7
等級 8: 3
【Top100作者碼齡分布】
碼齡 0: 15
碼齡 1: 14
碼齡 2: 23
碼齡 3: 12
碼齡 4: 13
碼齡 5: 12
碼齡 6: 4
碼齡 7: 2
碼齡10: 1
碼齡12: 1
碼齡13: 1
碼齡-1: 1
【Top100作者周排名分布】
周榜前100名 : 5
第100~200名 : 2
第200~500名 : 8
第500~1千名 : 5
第1千~5千名 : 17
第5千~1萬名 : 14
第1萬~2萬名 : 7
第2萬~5萬名 : 10
第5萬~10萬名 : 11
10萬名之后 : 20
代碼:
from requests import get from bs4 import BeautifulSoup as bs from win32com.shell import shell from datetime import datetime as dt from time import perf_counter from re import findall def lenB(str): t = 0 for s in str: if '\u4e00' <= s <= '\u9fef': t += 1 return t def reportTime(): d = dt.today() return f'{d.year}-{d.month:02}-{d.day:02} {d.hour:02}:{d.minute:02}' def reportData(Index, num=0): count = [0,0,0,0,0,0] for i in Index: if i[0] <= num : count[0]+=1 if i[1] <= num : count[1]+=1 if i[2] <= num : count[2]+=1 if sum(i[:2]) <= num : count[3]+=1 if sum(i[:3]) <= num : count[4]+=1 if i[-1]: count[-1]+=1 return count def reportData2(Index): count = [0,0,0,0,0,0] out1,out2 = (200,20,20),(100,10,10) for i in Index: if i[0] >= out1[0] : count[0]+=1 if i[0] >= out2[0] : count[1]+=1 if i[1] >= out1[1] : count[2]+=1 if i[1] >= out2[1] : count[3]+=1 if i[2] >= out1[2] : count[4]+=1 if i[2] >= out2[2] : count[5]+=1 return count def reportString(count): outStr = f'瀏覽為0的:\t{count[0]}\n評論為0的:\t' outStr += f'{count[1]}\n收藏為0的:\t{count[2]}\n' outStr += f'瀏覽評論0的:\t{count[3]}\n' outStr += f'三指標都0的:\t{count[4]}\n' return outStr def reportString2(count): outStr = f'瀏覽個位數(shù)的:\t{count[0]}\n' outStr += f'評論個位數(shù)的:\t{count[1]}\n' outStr += f'收藏個位數(shù)的:\t{count[2]}\n' outStr += f'無封面題圖的:\t{count[-1]}\n' return outStr def reportString3(count,idx=0): out1,out2 = (200,20,20),(100,10,10) if idx==0: out = out1 else: idx=1; out = out2 outStr = f'瀏覽>={out[0]}的:\t{count[idx]}\n' outStr += f'評論>={out[1]}的:\t{count[idx+2]}\n' outStr += f'收藏>={out[2]}的:\t{count[idx+4]}\n' return outStr def dictFromList(Values,num=5): tags,tagDict = [],dict() if num==5: for tag in Values: tags.extend(list(tag[num])) else: for tag in Values: tags.append(tag[num]) Tags = list(set(tags)) for t in Tags: tagDict[str(t)] = tags.count(t) return tagDict def matchRange(value): if 0<value<=100: res = 0 elif 100<value<=200: res = 1 elif 200<value<=500: res = 2 elif 500<value<=1000: res = 3 elif 1000<value<=5000: res = 4 elif 5000<value<=10000: res = 5 elif 10000<value<=20000: res = 6 elif 20000<value<=50000: res = 7 elif 50000<value<=100000: res = 8 else: res = 9 return res if __name__ == '__main__': desktop = shell.SHGetFolderPath(0, 25, None, 0) filename = r'\【CSDN排行榜Top100】'+reportTime()[:10]+'.txt' output = desktop + filename tofile = open(output,'w',encoding='utf-8') rank,ids,articles,index = [],[],[],[] print('\n開始爬取熱榜,請稍候...') print('\n【CSDN 綜合熱榜】:\n', file=tofile) agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.' agent += '36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36' website = 'https://blog.csdn.net/phoenix/web/blog/' for i in range(4): url = website + f'hotRank?page={i}&pageSize=25' res = get(url,headers={'User-Agent':agent}).json() if res["code"] == 200: data = res["data"] rank += [r for r in data] print(f'耗時:{perf_counter()}s\n') rank = [[v for i,v in r.items()] for r in rank] for i,r in enumerate(rank): d,m = divmod(i,25) if m==0: count = 0 print(f'【{d*25+1}到{d*25+25}名】:\n', file=tofile) if r[5].lower(): count += 1 ids.append(r[5]) articles.append(r[7]) print(f'★№{i+1:02}:{r[3]} (熱度:{r[0]})\n○《{r[6]}》', file=tofile) print(f'◎ 瀏覽:{r[-5]} 評論:{r[-4]} 收藏:{r[-3]}', file=tofile) print(f'¤ {r[7]}\n', file=tofile) index.append((int(r[-3]),int(r[-5]),int(r[-4]),int(r[0]),r[-1]==[])) count1 = reportData(index) outStr1 = '【Top100指標統(tǒng)計】\n\n' outStr1 += reportString(count1) count1_2 = reportData(index,9) outStr1_2 = reportString2(count1_2) count1_3 = reportData2(index) outStr1_3 = reportString3(count1_3,1) print(outStr1, file=tofile) print(outStr1_2, file=tofile) print(outStr1_3, file=tofile) count2 = reportData(index[:50]) outStr2 = '【Top50指標統(tǒng)計】\n\n' outStr2 += reportString(count2) count2_2 = reportData(index[:50],9) outStr2_2 = reportString2(count2_2) count2_3 = reportData2(index) outStr2_3 = reportString3(count1_3) print(outStr2, file=tofile) print(outStr2_2, file=tofile) print(outStr2_3, file=tofile) #標題關(guān)鍵字,可根據(jù)需要自行添加 keywords = ('C++','C語言','Python','JAVA','Delphi','C#','mysql','HTML', 'Matlab','Unity','Spring','Nginx', 'Windows','Linux','Android','Ubuntu', '框架','算法','對象','函數(shù)','爬蟲') kwIndex = [] for _ in range(len(keywords)): kwIndex.append(0) for title in rank: for i,kw in enumerate(keywords): if kw.lower() in title[6].lower(): kwIndex[i] += 1 outStr3 = '\n【Top100標題常見關(guān)鍵字統(tǒng)計】\n\n' for i,kw in enumerate(kwIndex): if i==1: kwi,kws = kw + kwIndex[0],'C/C++' else: kwi,kws = kw,keywords[i].title() if i>=1 and kwi>0: outStr3 += f'{kws:<{10-lenB(kws)}}: {kwi}\n' ''' #字典形式可以排序 kwDict = dict() for i,kw in enumerate(keywords): kwDict[kw] = kwIndex[i] for item in sorted(kwDict.items(),key=lambda k:k[1],reverse=True): if not item[1]: print();break print(f'{item[0]:<{10-lenB(item[0])}}: {item[1]}') ''' print(outStr1 + '\n' + outStr1_2 + '\n' + outStr1_3) print(outStr2 + '\n' + outStr2_2 + '\n' + outStr2_3) #爬取Top100資料 Values = [] print('開始爬取Top100網(wǎng)頁,請稍候(大約1分鐘)...') timer = perf_counter() for idx,url in enumerate(articles): res = get(url,headers={'User-Agent':agent}) res.encoding='uft-8' soup = bs(res.text,'html.parser') value = [] for i in range(3,8): if i!=4: value.append(rank[idx][i]) try: #碼齡 ctxt = 'personal-home-page personal-home-years' html = soup.find('span',class_=ctxt) value.append(int(findall(r'\d+',html.text)[0])) except: value.append(-1) try: #標簽 ctxt = 'tags-box artic-tag-box' html = soup.find('div',class_=ctxt) html = html.find_all('a') value.append(set([i.text.strip().lower().title() for i in html])) except: value.append(set()) html = soup.find_all('dl') for dl in range(1,len(html)): try: dlval = html[dl]['title'] except: break if '級' in dlval: dlval = dlval[:dlval.find('級')] if '暫無排名' in dlval: dlval = -1 value.append(int(dlval)) if len(value)==16: value.append(False) else: value.append(True) Values.append(value) print(f'耗時:{perf_counter()-timer}s') datafile = desktop + r'\【CSDN排行榜Top100】data'+reportTime()[:10]+'.txt' #收集到的數(shù)據(jù)全部寫入文件*data*.txt failVals = 0 with open(datafile,'w',encoding='utf-8') as f: f.write(f'#報告日期:{reportTime()}\n') for val in Values: if val[-1]: failVals += 1 continue f.writelines('|'.join([str(i) for i in val])) f.write('\n') Values = [val for val in Values if not val[-1]] print(f'下載失敗數(shù):{failVals}\n') '''value列表各元素的索引值分別代表: 0~ 5:昵稱 用戶名 標題 鏈接 碼齡 文章標簽 6~10:原創(chuàng) 周排名 總排名 訪問 等級 11~15:積分 粉絲 獲贊 評論 收藏 16: 失敗標記=False''' #輸出內(nèi)容 tagsRank,tagDict = [],dictFromList(Values) for item in sorted(tagDict.items(),key=lambda t:t[1],reverse=True): tagsRank.append(f'{item[0]:<{22-lenB(item[0])}}: {item[1]}') if len(tagsRank)>=100: break outStr4 = lambda x:f'\n【Top100文章標簽排名(Top{x})】\n' outStr5 = '\n【Top100博客等級分布】\n\n' valDict = dictFromList(Values,10) for key,value in valDict.items(): outStr5 += f'等級{key:>2}: {value}\n' print(outStr5, file=tofile) outStr6 = '\n【Top100作者碼齡分布】\n\n' valDict = dictFromList(Values,4) for key,value in valDict.items(): outStr6 += f'碼齡{key:>2}: {value}\n' print(outStr6, file=tofile) outStr7 = '\n【Top100作者周排名分布】\n\n' valDict = dictFromList(Values,7) weekRank = [0 for _ in range(10)] for key,value in valDict.items(): weekRank[matchRange(int(key))] += 1 textRank = ('周榜前100名','第100~200名','第200~500名','第500~1千名','第1千~5千名', '第5千~1萬名','第1萬~2萬名','第2萬~5萬名','第5萬~10萬名','10萬名之后') for i,txt in enumerate(textRank): outStr7 += f'{txt:<{14-lenB(txt)}}: {weekRank[i]}\n' print(outStr7, file=tofile) #更多指標可用以分析或者畫折線圖柱形圖等等,指標索引見上面的注釋 print(outStr5 + outStr6 + outStr7) print(f'更多詳情見桌面文件:\n{filename[1:]}') endStr = '='*26 endStr += f'\n報告日期:{reportTime()[:10]}' endStr += f'\n報告時間:{reportTime()[11:]}' endStr += f'\n程序耗時:{round(perf_counter(),2)}s\n' print(outStr3, file=tofile) print(outStr4(100), file=tofile) for t in tagsRank: print(t, file=tofile) print(endStr, file=tofile) tofile.close() print(endStr) ''' 運行環(huán)境: Windows7 + Python3.8.8 ''' ''' Written by Hann, 2021.10.25 '''
代碼比較亂,這就是業(yè)余風格⊙﹏⊙‖∣ 程序一共抓取了16種信息,可以根據(jù)需要,增加對其他各種數(shù)據(jù)時行分析。比如,還能用matplotlib來把數(shù)據(jù)畫成圖表:
例一:
Top100的熱度衰減表
import matplotlib.pyplot as plt plt.figure().canvas.set_window_title('CSDN Top100 熱度衰減示意圖') plt.title('Top100 Attenuation Diagram') hots = [h[3] for h in index] x = [i+1 for i in range(len(hots))] plt.plot(x, hots) plt.show()
例二:
Top100 博客等級分布圖
import matplotlib.pyplot as plt plt.figure().canvas.set_window_title('CSDN Top100 博客等級分布示意圖') Level = [i[10] for i in Values] x = [i+1 for i in range(len(Level))] plt.scatter(x, Level,marker='o') plt.show()
注: 以上兩代碼中的 index 和 Values 兩個列表是原爬蟲程序中的全局變量,為省事我直接用了。同樣的還有一個變量tagDict可以直接拿來用的:
tagDict
{'紅書《題目與解讀》': 1, '# Java Web': 1, '負載均衡': 1, 'String': 1, 'Html': 1, '編程入門': 1, 'Python爬蟲': 1, '原力計劃': 5, 'React.Js': 1, '模板': 1, 'Flutter': 1, 'Python Qt': 1, 'Leetcode題解集錦': 1, '搜索引擎': 1, '基礎(chǔ)知識': 1, '后端': 8, 'Flutter騷操作': 1, 'Spring Boot': 2, 'Elasticsearch': 3, '架構(gòu)': 1, 'Database': 3, 'Nginx': 3, '1024程序員節(jié)': 23, 'Waf攻防': 1, '計算機網(wǎng)絡(luò)': 1, '程序員生存技能': 1, '二叉樹': 1, '泛型類': 1, '日期工具類': 1, '拍賣': 1, 'Web前端': 1, 'Date': 1, '排序算法': 2, 'Javascript': 9, '源碼分析': 1, '數(shù)據(jù)分析': 1, '大數(shù)據(jù)': 3, 'Linux': 6, '數(shù)據(jù)庫': 5, 'Pycharm': 1, 'Vue.Js': 5, '操作系統(tǒng)': 2, '單片機': 1, '生活感悟': 1, 'Java成神之路之設(shè)計模式': 1, 'Create-Vue': 1, '藍橋杯': 1, '貪心': 1, '【詳細注釋】數(shù)據(jù)結(jié)構(gòu)與算法': 1, '項目': 1, 'Matlab': 1, 'Jdbc': 1, '微信小程序': 1, '# 中間件': 1, 'Bash': 1, 'Leetcode': 3, '同步': 1, '數(shù)據(jù)庫應(yīng)用': 1, '棧': 1, 'Language': 1, '開發(fā)語言': 10, 'Jwt': 1, 'Css': 3, 'Mysql': 1, '操作系統(tǒng)篇': 1, 'Vj': 1, 'Sqlite': 1, 'Java基礎(chǔ)': 1, 'Spring': 4, '計算機網(wǎng)絡(luò)養(yǎng)成': 1, '機器人': 1, 'Centos': 1, '機器視覺': 1, 'Kube-Controller-Manager': 1, '網(wǎng)絡(luò)編程專題': 1, '從零開始Python+微信小程序開發(fā)': 1, 'C語言': 4, 'Spring Security': 1, '泛型': 1, '面試': 1, 'Elastic': 1, '讀論文': 1, '數(shù)據(jù)處理': 1, '服務(wù)器': 3, '重學(xué)Java高并發(fā)': 1, '云原生': 1, 'Java': 25, '線性回歸': 1, '基數(shù)排序': 1, '網(wǎng)絡(luò)': 2, 'Rabbitmq': 1, 'Js': 1, '上位機': 1, 'Java基礎(chǔ)概要': 1, 'React系列': 1, 'Qt': 1, '分類': 1, '網(wǎng)絡(luò)協(xié)議': 1, '多線程': 1, '數(shù)據(jù)庫開發(fā)': 1, 'Vue': 4, 'Jvm': 1, '常用算法考題': 1, '跨域': 1, 'Visio': 1, 'Es6': 2, '源碼': 1, 'Synchronized': 1, '算法之力扣系列': 1, '老王和他的It界朋友們': 1, 'C++語言': 1, '進程管理': 1, '層序遍歷': 1, 'Wireshark': 1, '知識點': 1, '經(jīng)驗分享': 1, 'Javascript百煉成仙(試讀)': 1, 'Hibernate': 1, '運維': 2, '數(shù)據(jù)結(jié)構(gòu)與算法': 1, '雙指針': 1, '教程': 1, 'Python': 8, '# Python科學(xué)計算基礎(chǔ)': 1, '編譯原理': 1, 'Big Data': 2, '數(shù)據(jù)結(jié)構(gòu)': 2, '程序人生': 1, 'Linux相關(guān)命令': 1, '單調(diào)棧': 1, '圖像處理': 2, 'Oauth2': 1, 'Qclipboard': 1, 'Jupyter': 1, 'Lintcode算法': 1, 'Opengauss經(jīng)驗總結(jié)': 1, 'C++': 5, 'Springboot': 2, '算法設(shè)計': 1, 'Redis': 2, '刷題筆記': 1, '雜文': 1, 'Ecmascript': 2, 'Linux學(xué)習': 1, '剪貼數(shù)據(jù)類': 1, '基于Matlab與Fpga的數(shù)字圖像處理': 1, '前端': 9, 'Opencv': 2, 'Android項目記錄': 1, '人工智能學(xué)習之路': 1, '算法': 8, '分布式事務(wù)': 1, 'Epoll': 1, '復(fù)習': 1, 'Http': 1, 'C語言筆記': 1, 'Anaconda': 1, '計算機視覺': 1, '其他': 1, 'Npm': 1, 'Sso': 1, 'Gui設(shè)計': 1, 'Array': 1, '筆記': 3, '安裝': 1, 'Kubernetes': 1, 'Sqlserver': 1, '泛型方法': 1, '# Spring': 1, '分布式': 1, 'Ros機械臂': 1, 'Docker': 1, '鏈表': 1, 'Css3': 2, 'Android': 1, '微服務(wù)': 1, 'Python計算機視覺': 1, '分布式&Amp;高并發(fā)': 1, '排序': 1}
這個變量可以用模塊wordcloud (中文分詞需要jieba模塊配合)加工一下,生成Top100熱榜文章的標簽詞云圖。(本篇完)
到此這篇關(guān)于Python爬蟲之對CSDN榜單進行分析的文章就介紹到這了,更多相關(guān)Python爬蟲案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python7個爬蟲小案例詳解(附源碼)下篇
- Python7個爬蟲小案例詳解(附源碼)中篇
- Python7個爬蟲小案例詳解(附源碼)上篇
- 利用Python爬蟲爬取金融期貨數(shù)據(jù)的案例分析
- Python爬蟲采集Tripadvisor數(shù)據(jù)案例實現(xiàn)
- Python?Ajax爬蟲案例分享
- Python爬蟲入門案例之爬取去哪兒旅游景點攻略以及可視化分析
- Python爬蟲入門案例之爬取二手房源數(shù)據(jù)
- Python爬蟲入門案例之回車桌面壁紙網(wǎng)美女圖片采集
- Python爬蟲之Scrapy環(huán)境搭建案例教程
- 用Python爬蟲破解滑動驗證碼的案例解析
- python爬蟲系列網(wǎng)絡(luò)請求案例詳解
- python爬蟲破解字體加密案例詳解
- python爬蟲線程池案例詳解(梨視頻短視頻爬取)
- python爬蟲scrapy框架的梨視頻案例解析
- python爬蟲利器之requests庫的用法(超全面的爬取網(wǎng)頁案例)
- Python爬蟲實戰(zhàn)案例之爬取喜馬拉雅音頻數(shù)據(jù)詳解
- Python爬蟲Scrapy框架CrawlSpider原理及使用案例
相關(guān)文章
Python數(shù)據(jù)結(jié)構(gòu)棧實現(xiàn)進制轉(zhuǎn)換簡單示例
眾所周知計算機的內(nèi)存都是以二進制的形式進行數(shù)據(jù)存儲,下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)結(jié)構(gòu)棧實現(xiàn)進制轉(zhuǎn)換的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02python3 googletrans超時報錯問題及翻譯工具優(yōu)化方案 附源碼
這篇文章主要介紹了python3 googletrans超時報錯問題及翻譯工具優(yōu)化方案 附源碼,本文給大家分享解決方法,通過實例代碼相結(jié)合給大家介紹的非常詳細,需要的朋友可以參考下2020-12-12詳解Python中的時間格式的讀取與轉(zhuǎn)換(time模塊)
這篇文章主要介紹了Python中的時間格式的讀取與轉(zhuǎn)換(time模塊),文末給大家介紹了python的時間獲取與轉(zhuǎn)化:time模塊和datetime模塊的相關(guān)知識,需要的朋友可以參考下2023-05-05