婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > Python爬蟲分析匯總

Python爬蟲分析匯總

熱門標簽:沈陽防封電銷電話卡 萊蕪電信外呼系統 地圖標注多個 銀川電話機器人電話 鶴壁手機自動外呼系統違法嗎 企業微信地圖標注 怎么辦理400客服電話 B52系統電梯外呼顯示E7 高德地圖標注收入咋樣

Python爬蟲分析

前言:

計算機行業的發展太快了,有時候幾天不學習,就被時代所拋棄了,因此對于我們程序員而言,最重要的就是要時刻緊跟業界動態變化,學習新的技術,但是很多時候我們又不知道學什么好,萬一學的新技術并不會被廣泛使用,太小眾了對學習工作也幫助不大,這時候我們就想要知道大佬們都在學什么了,跟著大佬學習走彎路的概率就小很多了。現在就讓我們看看C站大佬們平時都收藏了什么,大佬學什么跟著大佬的腳步就好了!

一、程序說明

通過爬取 “CSDN” 獲取全站排名靠前的博主的公開收藏夾,寫入 csv 文件中,根據所獲取數據分析領域大佬們的學習趨勢,并通過可視化的方式進行展示。

二、數據爬取

使用 requests 庫請求網頁信息,使用 BeautifulSoup4 json 庫解析網頁。

1、獲取 CSDN 作者總榜數據

首先,我們需要獲取 CSDN 中在榜的大佬,獲取他/她們的相關信息。由于數據是動態加載的 (因此使用開發者工具,在網絡選項卡中可以找到請求的 JSON 數據:

觀察請求鏈接:

https://blog.csdn.net/phoenix/web/blog/all-rank?page=0pageSize=20
https://blog.csdn.net/phoenix/web/blog/all-rank?page=1pageSize=20
...

可以發現每次請求 JSON 數據時,會獲取20個數據,為了獲取排名前100的大佬數據,使用如下方式構造請求:

url_rank_pattern = "https://blog.csdn.net/phoenix/web/blog/all-rank?page={}pageSize=20"

for i in range(5):
    url = url_rank_pattern.format(i)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

請求得到 Json 數據后,使用 json 模塊解析數據(當然也可以使用 re 模塊,根據自己的喜好選擇就好了),獲取用戶信息,從需求上講,這里僅需要用戶 userName,因此僅解析 userName 信息,也可以根據需求獲取其他信息:

userNames = []
information = json.loads(str(soup))
for j in information['data']['allRankListItem']:
    # 獲取id信息
    userNames.append(j['userName'])

2、獲取收藏夾列表

獲取到大佬的 userName 信息后,通過主頁來觀察收藏夾列表的請求方式,本文以自己的主頁為例(給自己推廣一波),分析方法與上一步類似,在主頁中切換到“收藏”選項卡,同樣利用開發者工具的網絡選項卡:

觀察請求收藏夾列表的地址:

https://blog.csdn.net/community/home-api/v1/get-favorites-created-list?page=1size=20noMore=falseblogUsername=LOVEmy134611

可以看到這里我們上一步獲取的 userName 就用上了,可以通過替換 blogUsername 的值來獲取列表中大佬的收藏夾列表,同樣當收藏夾數量大于20時,可以通過修改 page 值來獲取所有收藏夾列表:

collections = "https://blog.csdn.net/community/home-api/v1/get-favorites-created-list?page=1size=20noMore=falseblogUsername={}"
for userName in userNames:
    url = collections.format(userName)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

請求得到 Json 數據后,使用 json 模塊解析數據,獲取收藏夾信息,從需求上講,這里僅需要收藏夾 id,因此僅解析 id 信息,也可以根據需求獲取其他信息(例如可以獲取關注人數等信息,找到最受歡迎的收藏夾):

file_id_list = []
information = json.loads(str(soup))
# 獲取收藏夾總數
collection_number = information['data']['total']
# 獲取收藏夾id
for j in information['data']['list']:
    file_id_list.append(j['id'])

這里大家可能會問,現在 CSDN 不是有新舊兩種主頁么,請求方式能一樣么?答案是:不一樣,在瀏覽器端進行訪問時,舊版本使用了不同的請求接口,但是我們同樣可以使用新版本的請求方式來進行獲取,因此就不必區分新、舊版本的請求接口了,獲取收藏數據時情況也是一樣的。

3、獲取收藏數據

最后,單擊收藏夾展開按鈕,就可以看到收藏夾中的內容了,然后同樣利用開發者工具的網絡選項卡進行分析:

觀察請求收藏夾的地址:

https://blog.csdn.net/community/home-api/v1/get-favorites-item-list?blogUsername=LOVEmy134611folderId=9406232page=1pageSize=200

可以看到剛剛獲取的用戶 userName 和收藏夾 id 就可以構造請求獲取收藏夾中的收藏信息了:

file_url = "https://blog.csdn.net/community/home-api/v1/get-favorites-item-list?blogUsername={}folderId={}page=1pageSize=200"
for file_id in file_id_list:
    url = file_url.format(userName,file_id)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')

最后用 re 模塊解析:

    user = user_dict[userName]
    user = preprocess(user)
    # 標題
    title_list  = analysis(r'"title":"(.*?)",', str(soup))
    # 鏈接
    url_list = analysis(r'"url":"(.*?)"', str(soup))
    # 作者
    nickname_list = analysis(r'"nickname":"(.*?)",', str(soup))
    # 收藏日期
    date_list = analysis(r'"dateTime":"(.*?)",', str(soup))
    for i in range(len(title_list)):
        title = preprocess(title_list[i])
        url = preprocess(url_list[i])
        nickname = preprocess(nickname_list[i])
        date = preprocess(date_list[i])

4、爬蟲程序完整代碼

import time
import requests
from bs4 import BeautifulSoup
import os
import json
import re
import csv

if not os.path.exists("col_infor.csv"):
    #創建存儲csv文件存儲數據
    file = open('col_infor.csv', "w", encoding="utf-8-sig",newline='')
    csv_head = csv.writer(file)
    #表頭
    header = ['userName','title','url','anthor','date']
    csv_head.writerow(header)
    file.close()

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'
}

def preprocess(string):
    return string.replace(',',' ')

url_rank_pattern = "https://blog.csdn.net/phoenix/web/blog/all-rank?page={}pageSize=20"

userNames = []
user_dict = {}
for i in range(5):
    url = url_rank_pattern.format(i)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')
    information = json.loads(str(soup))
    for j in information['data']['allRankListItem']:
        # 獲取id信息
        userNames.append(j['userName'])
        user_dict[j['userName']] = j['nickName']

def get_col_list(page,userName):
    collections = "https://blog.csdn.net/community/home-api/v1/get-favorites-created-list?page={}size=20noMore=falseblogUsername={}"
    url = collections.format(page,userName)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')
    information = json.loads(str(soup))
    return information

def analysis(item,results):
    pattern = re.compile(item, re.I|re.M)
    result_list = pattern.findall(results)
    return result_list

def get_col(userName, file_id, col_page):
    file_url = "https://blog.csdn.net/community/home-api/v1/get-favorites-item-list?blogUsername={}folderId={}page={}pageSize=200"
    url = file_url.format(userName,file_id, col_page)
    #聲明網頁編碼方式
    response = requests.get(url=url, headers=headers)
    response.encoding = 'utf-8'
    response.raise_for_status()
    soup = BeautifulSoup(response.text, 'html.parser')
    user = user_dict[userName]
    user = preprocess(user)
    # 標題
    title_list  = analysis(r'"title":"(.*?)",', str(soup))
    # 鏈接
    url_list = analysis(r'"url":"(.*?)"', str(soup))
    # 作者
    nickname_list = analysis(r'"nickname":"(.*?)",', str(soup))
    # 收藏日期
    date_list = analysis(r'"dateTime":"(.*?)",', str(soup))
    for i in range(len(title_list)):
        title = preprocess(title_list[i])
        url = preprocess(url_list[i])
        nickname = preprocess(nickname_list[i])
        date = preprocess(date_list[i])
        if title and url and nickname and date:
            with open('col_infor.csv', 'a+', encoding='utf-8-sig') as f:
                f.write(user + ',' + title + ',' + url + ',' + nickname + ',' + date  + '\n')

    return information

for userName in userNames:
    page = 1
    file_id_list = []
    information = get_col_list(page, userName)
    # 獲取收藏夾總數
    collection_number = information['data']['total']
    # 獲取收藏夾id
    for j in information['data']['list']:
        file_id_list.append(j['id'])
    while collection_number > 20:
        page = page + 1
        collection_number = collection_number - 20
        information = get_col_list(page, userName)
        # 獲取收藏夾id
        for j in information['data']['list']:
            file_id_list.append(j['id'])
    collection_number = 0

    # 獲取收藏信息
    for file_id in file_id_list:
        col_page = 1
        information = get_col(userName, file_id, col_page)
        number_col = information['data']['total']
        while number_col > 200:
            col_page = col_page + 1
            number_col = number_col - 200
            get_col(userName, file_id, col_page)
    number_col = 0

5、爬取數據結果

展示部分爬取結果:

三、數據分析及可視化

最后使用 wordcloud 庫,繪制詞云展示大佬收藏。

from os import path
from PIL import Image
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, STOPWORDS
import pandas as pd
import matplotlib.ticker as ticker
import numpy as np
import math
import re

df = pd.read_csv('col_infor.csv', encoding='utf-8-sig',usecols=['userName','title','url','anthor','date'])

place_array = df['title'].values
place_list = ','.join(place_array)
with open('text.txt','a+') as f:
    f.writelines(place_list)

###當前文件路徑
d = path.dirname(__file__)

# Read the whole text.
file = open(path.join(d, 'text.txt')).read()
##進行分詞
#停用詞
stopwords = ["的","與","和","建議","收藏","使用","了","實現","我","中","你","在","之"]
text_split = jieba.cut(file)  # 未去掉停用詞的分詞結果   list類型

#去掉停用詞的分詞結果  list類型
text_split_no = []
for word in text_split:
    if word not in stopwords:
        text_split_no.append(word)
#print(text_split_no)

text =' '.join(text_split_no)
#背景圖片
picture_mask = np.array(Image.open(path.join(d, "path.jpg")))
stopwords = set(STOPWORDS)
stopwords.add("said")
wc = WordCloud(  
    #設置字體,指定字體路徑
    font_path=r'C:\Windows\Fonts\simsun.ttc', 
    # font_path=r'/usr/share/fonts/wps-office/simsun.ttc', 
    background_color="white",   
    max_words=2000,   
    mask=picture_mask,  
    stopwords=stopwords)  
# 生成詞云
wc.generate(text)

# 存儲圖片
wc.to_file(path.join(d, "result.jpg"))

到此這篇關于Python爬蟲分析匯總的文章就介紹到這了,更多相關Python爬蟲內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:
  • 關于python爬蟲應用urllib庫作用分析
  • python爬蟲Scrapy框架:媒體管道原理學習分析
  • python爬蟲Mitmproxy安裝使用學習筆記
  • Python爬蟲和反爬技術過程詳解
  • python爬蟲之Appium爬取手機App數據及模擬用戶手勢
  • 爬蟲Python驗證碼識別入門
  • Python爬蟲技術
  • Python爬蟲爬取商品失敗處理方法
  • Python獲取江蘇疫情實時數據及爬蟲分析
  • Python爬蟲之Scrapy環境搭建案例教程
  • Python爬蟲中urllib3與urllib的區別是什么
  • 教你如何利用python3爬蟲爬取漫畫島-非人哉漫畫

標簽:烏魯木齊 葫蘆島 湘西 安慶 三亞 銀川 呼倫貝爾 呼倫貝爾

巨人網絡通訊聲明:本文標題《Python爬蟲分析匯總》,本文關鍵詞  Python,爬蟲,分析,匯總,Python,;如發現本文內容存在版權問題,煩請提供相關信息告之我們,我們將及時溝通與處理。本站內容系統采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 下面列出與本文章《Python爬蟲分析匯總》相關的同類信息!
  • 本頁收集關于Python爬蟲分析匯總的相關信息資訊供網民參考!
  • 推薦文章
    主站蜘蛛池模板: 买车| 沙雅县| 铅山县| 曲水县| 襄汾县| 长治县| 略阳县| 石景山区| 临夏县| 武穴市| 巫山县| 蒙山县| 澜沧| 梓潼县| 武陟县| 乌什县| 万州区| 定边县| 子长县| 巴塘县| 芜湖县| 饶阳县| 鄂托克前旗| 平果县| 北川| 奇台县| 剑河县| 佛山市| 怀远县| 西充县| 延安市| 五常市| 阿克苏市| 承德市| 苏尼特右旗| 新竹市| 同德县| 法库县| 绍兴市| 星子县| 奉化市|