簡單的用Python來獲取微博評論,制作詞云圖。
首先準(zhǔn)備環(huán)境模塊
環(huán)境使用
- Python 3.8或以上版本即可
- Pycharm 任意版本
模塊使用
import requests import wordcloud import jieba
?
以上三個模塊都需要安裝,直接pip install 加上模塊名安裝即可。
爬蟲基本流程
一. 數(shù)據(jù)來源分析
- 明確需求: 明確采集的網(wǎng)站以及數(shù)據(jù)內(nèi)容
- 網(wǎng)址: https://weibo.com/2803301701/NxcPMvW2l
- 數(shù)據(jù): 評論內(nèi)容 - 抓包分析: 通過開發(fā)者工具進行抓包
- 打開開發(fā)者工具: F12
- 刷新網(wǎng)頁
- 通過關(guān)鍵字查找對應(yīng)的數(shù)據(jù)
關(guān)鍵字: 評論的內(nèi)容
數(shù)據(jù)包地址: https://weibo.com/ajax/statuses/buildComments?is_reload=1&id=4979141627611265&is_show_bulletin=2&is_mix=0&count=10&uid=2803301701&fetch_level=0&locale=zh-CN
二. 代碼實現(xiàn)步驟
- 發(fā)送請求 -> 模擬瀏覽器對于url地址發(fā)送請求
- 獲取數(shù)據(jù) -> 獲取服務(wù)器返回響應(yīng)數(shù)據(jù)
- 解析數(shù)據(jù) -> 提取評論內(nèi)容
- 保存數(shù)據(jù) -> 保存本地文件 (文本 csv Excel 數(shù)據(jù)庫)
代碼展示
數(shù)據(jù)采集部分
1、發(fā)送請求 -> 模擬瀏覽器對于url地址發(fā)送請求
# 模擬瀏覽器 headers = { # Referer 防盜鏈 'Referer':'https://weibo.com/2803301701/NxcPMvW2l', # User-Agent 用戶代理 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } # 請求網(wǎng)址 url = 'https://weibo.com/ajax/statuses/buildComments' # 請求參數(shù) data = { 'is_reload': '1', 'id': '4979141627611265', 'is_show_bulletin': '2', 'is_mix': '0', 'max_id': max_id, 'uid': '2803301701', 'fetch_level': '0', 'locale': 'zh-CN', } # 發(fā)送請求 response = requests.get(url=url, params=data, headers=headers)
?
2、獲取數(shù)據(jù) -> 獲取服務(wù)器返回響應(yīng)數(shù)據(jù)
json_data = response.json() print(json_data)
?
3、解析數(shù)據(jù) -> 提取評論內(nèi)容
# 提取評論所在列表 content_list = json_data['data'] # for循環(huán)遍歷, 提取列表里面元素 for index in content_list: content = index['text_raw'] print(content)
?
4、保存數(shù)據(jù)
保存文本
with open('data.txt', mode='a', encoding='utf-8') as f: f.write(content) f.write('\n') print(content)
?
保存表格
with open('data.txt', mode='a', encoding='utf-8') as f: f.write(content) f.write('\n') print(content) df = pd.DataFrame(lis) df.to_excel(excel_writer:'data.xlsx', index=False) # 數(shù)據(jù)采集和可視化我還錄制了詳細的視頻講解 # 跟代碼一起打包好放在這個摳裙了 708525271
?
可視化部分
# 導(dǎo)入結(jié)巴分詞 import jieba # 導(dǎo)入詞云圖模塊 import wordcloud """詞云分析""" # 讀取文件內(nèi)容 f = open('data.txt', encoding='utf-8').read() # 分詞 txt = jieba.lcut(f) # 把列表合并成字符串 string = ' '.join(txt) # 制作詞云圖配置 wc = wordcloud.WordCloud( font_path='msyh.ttc', width=1000, # 寬 height=700, # 高 background_color='white', # 背景顏色 默認黑色 ) # 導(dǎo)入內(nèi)容 wc.generate(string) wc.to_file('詞云_3.png') print(txt)
?
詞云圖效果展示
?
好了,本次分享就結(jié)束了,下次再見!文章來源:http://www.zghlxwxcb.cn/news/detail-760550.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-760550.html
到了這里,關(guān)于簡單的用Python采集下微博評論,制作可視化詞云圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!