python爬蟲實戰(五) 爬取微博明星粉絲基本信息+可視化

一、微博爬蟲類型介紹

        微博有關的爬蟲,由於根據網址的不同,可分爲三種類型:

        1.移動端爬取:利用selenium去模擬登錄然後再去爬取,比較麻煩,但是可以根據個人需求依據關鍵詞進行指定爬取。

        2.手機端爬取:網址爲手機端微博網址,這在我之前的博客中也有提及微博超話內容爬取,在此不再贅述。無需登錄,利用Chrome進行抓包即可實現,而且較selenium來說,性能也是更高一點。(不過要注意設置隨機睡眠時間

        3.舊版網址爬取:這是微博最簡化版本的網址weibo.cn(感覺回到了諾基亞的年代),界面簡單無需抓包,直接利用正則或者xpath等方式提取即可(需要拿到登錄後的cookie值)

建議:如果只是爬取指定用戶的評論、基本信息這些,後兩種方法就夠用了;如果涉及到更復雜的需求時再考慮selenium爬取

二、明星粉絲信息爬蟲

舊版的網址,粉絲數量只顯示了前20頁,一頁10個,總共才200個。手機端下的粉絲列表總共也只能顯示5000個,對於5000個之後的粉絲信息,微博出於隱私保護,是爬取不了。詳細的情況可參考新浪微博如何獲取用戶全部粉絲列表

1.微博用戶URL說明:
舊版網址用戶首頁的URL爲:http://weibo.cn/u/用戶ID
手機端用戶首頁的URL爲:https://m.weibo.cn/u/用戶ID
以鄧紫棋爲例,她的ID爲1705586121,首頁如下:
在這裏插入圖片描述

她的粉絲信息抓包結果如下:
在這裏插入圖片描述
在這裏插入圖片描述
這裏的用戶信息只有用戶的簡介(screen_name)關注數(follow_count)粉絲數(follow_count),對應用戶性別和地區是沒有顯示的。

所以,考慮先用手機端爬取用戶ID,再用舊版網址登錄,提取信息。(舊版網址個人信息更全一些)

2.爬取鄧紫棋粉絲所有的user_id
考慮到部分用戶可能是機器人,初步篩選條件爲粉絲數大於等於20

import requests
import json
import random
import os
os.chdir('C:/Users/dell/Desktop')
import time
base_url='https://m.weibo.cn/api/container/getIndex?containerid=231051_-_fans_-_1705586121&since_id='
head=[
    "Opera/12.0(Windows NT 5.2;U;en)Presto/22.9.168 Version/12.00",
    "Opera/12.0(Windows NT 5.1;U;en)Presto/22.9.168 Version/12.00",
    "Mozilla/5.0 (Windows NT 5.1) Gecko/20100101 Firefox/14.0 Opera/12.0",
    "Opera/9.80 (Windows NT 6.1; WOW64; U; pt) Presto/2.10.229 Version/11.62",
    "Opera/9.80 (Windows NT 6.0; U; pl) Presto/2.10.229 Version/11.62",
]
header={
    'user-agent':random.choice(head)
}
with open('user_id.txt','w') as f:
    for page in range(2,251): #注意是從2開始纔是用戶信息
        try:
            url=base_url+str(page)
            r=requests.get(url,headers=header)
            data=json.loads(r.text)
            all_user=data['data']['cards'][0]['card_group']
            for user in all_user:
                fans=int(user.get('desc2').split(':')[1])
                if fans >=20:
                    f.write(str(user.get('user')['id'])+'\n')
            print('第{}頁用戶id爬取完畢'.format(page))
            time.sleep(random.randint(1,3))
        except:
            print('未爬到數據')

爬取的部分用戶ID如下:
在這裏插入圖片描述

3.以舊版本界面,爬取粉絲基本信息

import numpy as np
import pandas as pd
import requests
from lxml import etree
import random
import time
header={'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36',
       'cookie':'你自己的cookie',
       'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
       }
url_new='https://weibo.cn/u/'
data=[]
count=0  
def  get_id(path):
	with open(path,'r') as f:
		user_id=f.readlines()
		user_id=np.char.rstrip(user_list,'\n')
		return user_id
def gethtml(url,header):
    r=requests.get(url,headers=header)
    if r.status_code==200:
        return r.text
    else:
        print('網絡連接異常')
for user_id in get_id('user_id.txt'):
    try:
        url=url_new+user_id
        r_text=gethtml(url,header)
        html=etree.HTML(r_text.encode('utf-8'))
        user_name=html.xpath('//span[@class="ctt"]/text()')[0]
        inf=html.xpath('//span[@class="ctt"]/text()')[1]
        weibo_number=html.xpath('//div[@class="tip2"]/span[@class="tc"]/text()')[0].replace('微博','').strip('[]')
        focus_number=html.xpath('//div[@class="tip2"]/a[1]/text()')[0].replace('關注','').strip('[]')
        fan_number=html.xpath('//div[@class="tip2"]/a[2]/text()')[0].replace('粉絲','').strip('[]')
        data.append([user_name,inf,weibo_number,focus_number,fan_number])
        count+=1
        print('第{}個用戶信息寫入完畢'.format(count))
        time.sleep(random.randint(1,2))
    except:
        print('用戶信息不完全')
df=pd.DataFrame(data,columns=['user_id','inf','weibo_num','focus_num','fans_num'])
df.to_csv('weibo_user.csv',index=False,encoding='gbk')

最終爬取到粉絲數量大於等於20的用戶共1362個,清洗後的部分數據如下:
在這裏插入圖片描述

三、可視化

(1) 粉絲性別佔比

import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.rcParams['font.sans-serif']=['SimHei']
%config InlineBackend.figure_format='svg'
df=pd.read_csv('weibo_user.csv',encoding='gbk')
gender=pd.DataFrame(df['gender'].value_counts())
plt.pie(gender['gender'],
        labels=['女','男'],
        startangle=90,
        shadow=False,
        autopct='%1.1f%%',
        textprops={'fontsize': 13, 'color': 'w'},
        colors=['#f26d5b','#2EC4B6']
       )
plt.legend(loc='best')
plt.title('鄧紫棋粉絲性別佔比')
plt.axis('equal')   
plt.tight_layout()
plt.show()

從餅圖來看,女粉較男粉稍多一些

(2) 全國粉絲分佈情況
注意:使用的是pycharts最新版本

from pyecharts.charts import Map
from pyecharts import options as opts
loc=pd.DataFrame(df['loc'].value_counts()).drop(loc.index[0]) #去除其他
city=np.char.rstrip(list(loc.index))
map1=Map(init_opts=opts.InitOpts(width="1200px",height="800px"))
map1.set_global_opts(
    title_opts=opts.TitleOpts(title="鄧紫棋粉絲地區分佈"),
    visualmap_opts=opts.VisualMapOpts(max_=200, is_piecewise=True,
    pieces=[
    {"max": 200, "min": 150, "label": ">150", "color": "#754F44"},
    {"max": 149, "min": 100, "label": "100-149", "color": "#EC7357"},
    {"max": 99, "min": 50, "label": "50-99", "color": "#FDD692"},
    {"max": 49, "min": 1, "label": "1-49", "color": "#FBFFB9"},
    {"max": 0, "min": 0, "label": "0", "color": "#FFFFFF"},
    ], ))  #最大數據範圍,分段

map1.add("",[list(z) for z in zip(city,loc['loc'])],
maptype='china',is_roam=False,
        is_map_symbol_show=False)
map1.render('fans_loc.html')

在這裏插入圖片描述
從地區分佈來看,廣東粉最多,其次在四川、湖北、河南、山東、江蘇、浙江分佈較多

(3) 性別與地區交叉分佈情況

df_new=df[~df['loc'].isin(['其他'])]
index=df_new.groupby('loc').count().sort_values(by='gender',ascending=False).index
plt.figure(figsize=(15,6))
sns.countplot(data=df_new,x='loc',hue='gender',order=index,palette=['#f26d5b','#2EC4B6'])
plt.xticks(rotation=90)
plt.legend(loc='upper right')
plt.show()

在這裏插入圖片描述
大部分省份女粉是大於男粉的,也有部分地區如北京、上海、安徽等,男粉絲數量大於女粉數量。

(4) 用戶微博數、關注數、粉絲量基本情況

gender_group=df.pivot_table(aggfunc=np.mean,
                            index=df['gender'],
                           values=df[['weibo_num','focus_num','fans_num']]).round(0)

f,ax=plt.subplots(1,3,figsize=(15,6))
sns.barplot(x=gender_group.index,y=gender_group['weibo_num'],
            palette=['#f26d5b','#2EC4B6'],alpha=0.8,ax=ax[0])
ax[0].set_title('男女粉絲平均微博數')
ax[0].set_xlabel('性別')
ax[0].set_ylabel('平均微博數')

sns.barplot(x=gender_group.index,y=gender_group['focus_num'],
            palette=['#f26d5b','#2EC4B6'],alpha=0.8,ax=ax[1])
ax[1].set_title('男女粉絲平均關注數')
ax[1].set_xlabel('性別')
ax[1].set_ylabel('平均關注數')

sns.barplot(x=gender_group.index,y=gender_group['fans_num'],
            palette=['#f26d5b','#2EC4B6'],alpha=0.8,ax=ax[2])
ax[2].set_title('男女粉絲平均粉絲數')
ax[2].set_xlabel('性別')
ax[2].set_ylabel('平均粉絲數')
plt.suptitle('鄧紫棋粉絲微博基本信息') #子圖添加總標題
plt.show()

在這裏插入圖片描述

(5) 微博數、關注量、粉絲量相關性

plt.figure(figsize=(10,6))
sns.heatmap(df[['weibo_num','focus_num','fans_num']].corr(),cmap='YlGn',annot=True)
plt.title('微博數、關注數、粉絲數相關熱力圖')
plt.show()

在這裏插入圖片描述
相關係數的範圍在-1到1之間。越接近1,正相關性越強,越接近-1,負相關性越強。
從上圖來看,基本上三者之間的相關性還是很弱的,也就微博數與關注數相關性相對較高一點,但也沒有超過0.5。

需要原數據的可以在評論回覆"weibo"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章