本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理
本品文章來自騰訊云 作者:孤獨的明月
python手把手叫你分析CSDN個人博客資料
獲取個人的全部博客標題及鏈接,發布時間、瀏覽量、以及收藏量等資料資訊,按訪問量排序,整理成一份Excel表存盤,
使用時,輸入個人博客ID即可,從資料獲取到決議存盤,用到requests、BeautifulSoup、pandas等三方庫,一個完整的Python爬蟲實踐,


網頁分析
博客串列分析

通過分析我的博客串列網頁代碼,提取出每篇文章的鏈接,
我的博客串列url為:https://blog.csdn.net/xiaoma_2018/article/list/1?t=1
注意每個人的博客ID會不同,因此本爬蟲使用時要求輸入個人的博客ID及頁碼數,以達到通用的功能,
單篇博客分析

通過分析單篇博客的網頁原始碼,從其中獲取文章鏈接、文章標題、發布時間、瀏覽量、以及收藏量等資料資訊,
環境配置
本爬蟲程式,運行環境說明 PyCharm 2020.1.1、Python 3.7.5
使用到的第三方依賴庫如下:
執行:pip freeze > requirements.txt 匯出
beautifulsoup4==4.9.1 pandas==1.1.1 requests==2.24.0
代碼實作
代碼主要思路是:
- 要求輸入博客ID和頁面數
- 爬取全部博客鏈接
- 爬取每一篇博客的資料資訊
- 資料存盤
config 配置
為了方便爬取不同的博客ID網頁,單獨寫了入一個組態檔來定義爬蟲用到的引數及檔案路徑引數,config.py 檔案如下:
''' @Func 爬蟲程式用到的請求頭資訊及檔案路徑資訊 @File config.py ''' Host = "blog.csdn.net" # 請求頭host引數 User_Agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362" Source = 'html.txt' # 臨時保存博客串列html原始碼 EachSource = 'each.txt' # 臨時保存每篇博客html原始碼 OUTPUT = "博客資訊.csv" # 輸出博客資訊到 csv 檔案
其中,User_Agent必須根據自己的瀏覽器引數配置才能使用,其他引數可默認該配置,
run 代碼
''' @Func Python爬蟲CSDN博客文章資料,并寫入excel表中 使用 re 模塊正則匹配要獲取的 url地址 ''' import requests from bs4 import BeautifulSoup import pandas as pd import os import re from config import Host, User_Agent, Source, EachSource,OUTPUT results = [] # 存盤全部資料 def parseEachBlog(link): referer = "Referer: " + link headers = {"Referer": referer, "User-Agent": User_Agent} r = requests.post(link, headers=headers) html = r.text with open(EachSource, 'w', encoding='UTF-8') as f: f.write(html) soup = BeautifulSoup(open(EachSource, 'r', encoding='UTF-8'), features="html.parser") readcontent = soup.select('.bar-content .read-count') collection = soup.select('.bar-content .get-collection') readcounts = re.sub(r'\D', "", str(readcontent[0])) collections = re.sub(r'\D', "", str(collection[0])) blogname = soup.select('.title-article')[0].text time = soup.select('.bar-content .time')[0].text eachBlog = [blogname, link, readcounts, collections, time] return eachBlog def getBlogList(blogID, pages): listhome = "https://" + Host + "/" + blogID + "/article/list/" pagenums = [] # 轉換后的pages頁數 for i in range(1, int(pages)+1): pagenums.append(str(i)) for number in pagenums: url = listhome + number + "?t=1" headers = {"Referer": url, "Host": Host, "User-Agent": User_Agent} response = requests.post(url, headers=headers) html = response.text with open(Source, 'a', encoding='UTF-8') as f: f.write(html) # 獲取全部博客的鏈接 soup = BeautifulSoup(open(Source, 'r', encoding='UTF-8'), features="html.parser") hrefs = [] re_patterm = "^https://blog.csdn.net/" + blogID + "/article/details/\d+$" for a in soup.find_all('a', href=https://www.cnblogs.com/aa1273935919/p/True): if a.get_text(strip=True): href = a['href'] if re.match(re_patterm, href): if hrefs.count(href) == 0: hrefs.append(href) return hrefs def parseData(): results.sort(key=lambda result:int(result[2]), reverse=True) # 按瀏覽量排序 dataframe = pd.DataFrame(data=https://www.cnblogs.com/aa1273935919/p/results) dataframe.columns = ['文章標題', '文章鏈接', '瀏覽量', '收藏量', '發布時間'] dataframe.to_csv(OUTPUT, index=False, sep=',') def delTempFile(): if os.path.exists(Source): os.remove(Source) if os.path.exists(EachSource): os.remove(EachSource) if __name__ == '__main__': blogID = input("輸入你要爬去的博客名: ") pages = input("輸入博客串列頁數: ") print("獲取全部博客鏈接...") linklist = getBlogList(blogID, pages) print("開始獲取資料...") for i in linklist: print("當前獲取: %s"%(i)) results.append(parseEachBlog(i)) print("結束獲取資料...") # 開始決議并存盤 .csv 檔案 print("開始決議并存盤資料...") parseData() print("洗掉臨時檔案...") delTempFile()
執行程序
以我自己的博客ID為例,來展示一下執行的程序及結果,我的博客串列目前兩頁,
開始執行
結束執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/238345.html
標籤:Python
