目錄
一、前言
二、使用Python爬取輿情數(shù)據(jù)
1.安裝requests庫
2.分析數(shù)據(jù)
3.爬取數(shù)據(jù)
三、通過代理IP提高數(shù)據(jù)爬取效率
1.獲取代理IP
2.使用代理IP
四、使用Flask框架實現(xiàn)輿情監(jiān)控可視化系統(tǒng)
五、使用MongoDB存儲數(shù)據(jù)
六、總結(jié)
一、前言
在當(dāng)今社會,輿情監(jiān)控越來越被重視。隨著互聯(lián)網(wǎng)技術(shù)的發(fā)展,我們從傳統(tǒng)媒體渠道、官方報告、調(diào)查問卷等方式搜集到的輿情信息,逐漸被網(wǎng)絡(luò)上的內(nèi)容所替代。因為網(wǎng)絡(luò)上的內(nèi)容傳播速度快、及時性強、覆蓋范圍廣,成為了管理者、企業(yè)、政府等了解社會大眾情緒、掌握市場動向的重要途徑。
本文介紹如何基于Flask框架,使用Python語言編寫一個高校輿情分析,輿情監(jiān)控可視化系統(tǒng)。下面主要涉及5個方面:
- 如何使用Python爬取輿情數(shù)據(jù);
- 如何通過代理IP提高數(shù)據(jù)爬取效率;
- 如何使用Flask框架實現(xiàn)輿情監(jiān)控可視化系統(tǒng);
- 如何使用MongoDB存儲數(shù)據(jù);
- 如何使用ECharts實現(xiàn)數(shù)據(jù)可視化展示。
二、使用Python爬取輿情數(shù)據(jù)
爬取輿情數(shù)據(jù)主要有兩種方式,一種是直接使用API接口,通過調(diào)用API獲取相應(yīng)的數(shù)據(jù)。另一種方式是使用Python爬取網(wǎng)站上的數(shù)據(jù)。
本文介紹的是第二種數(shù)據(jù)獲取方式,以爬取中國大學(xué)排名網(wǎng)為例。
1.安裝requests庫
使用Python爬取網(wǎng)站數(shù)據(jù),首先需要安裝requests庫,requests庫是Python中的HTTP客戶端庫,能夠模擬HTTP請求,發(fā)送請求、接收響應(yīng)。使用以下命令進行安裝:
!pip install requests
2.分析數(shù)據(jù)
在爬取數(shù)據(jù)前,我們需要分析數(shù)據(jù)。打開中國大學(xué)排名網(wǎng),點擊“大學(xué)排名”->“全球排名”,網(wǎng)站鏈接為:http://www.zuihaodaxue.com/ARWU2020.html 。
從網(wǎng)站中我們可以看到展示的數(shù)據(jù)大致如下:
我們需要獲取的數(shù)據(jù)列為“排名”、“學(xué)校名稱”、“所在地區(qū)”、“總分”。
3.爬取數(shù)據(jù)
分析完數(shù)據(jù)之后,我們就可以開始爬取數(shù)據(jù)。首先,我們需要導(dǎo)入requests庫、BeautifulSoup庫。
import requests
from bs4 import BeautifulSoup
接著,我們需要設(shè)置請求頭和請求參數(shù),這里我們設(shè)置如下:
headers = {
? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
params = {
? ? 'from': 'hao360',
? ? 'ie': 'utf-8',
? ? 'query': 'python'}
其中,headers為請求頭,用于告訴服務(wù)器我們的身份信息,params為請求參數(shù),表示要搜索“python”關(guān)鍵詞。
接著,我們使用requests庫發(fā)送請求,獲取網(wǎng)頁內(nèi)容,并解析所需的數(shù)據(jù)。
url = 'http://www.zuihaodaxue.com/ARWU2020.html'
response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')
all_university = soup.findAll('tr', {'class': 'bgfd'})
for university in all_university:
? ? rank = university.find('td', {'align': 'center'}).getText()
? ? name = university.find('a').getText()
? ? region = university.find('div', {'style': 'padding-left:10px;'}).getText().strip()
? ? score = university.findAll('td', {'align': 'center'})[-1].getText()
? ? print(rank, name, region, score)
這樣,我們就可以獲取到所有大學(xué)的排名、學(xué)校名稱、所在地區(qū)、總分數(shù)據(jù)。
不過需要注意,如果直接爬取網(wǎng)站,可能會被封IP,下一節(jié)會介紹如何通過代理IP提高數(shù)據(jù)爬取效率。
三、通過代理IP提高數(shù)據(jù)爬取效率
當(dāng)我們爬取數(shù)據(jù)時,如果頻繁訪問同一個網(wǎng)站,可能會被檢測到,從而導(dǎo)致IP被封,無法正常訪問。這時候,我們可以使用代理IP來避免這個問題,使用代理IP進行數(shù)據(jù)爬取,可以更好地保護我們的真實IP,達到更好的效果。
1.獲取代理IP
在互聯(lián)網(wǎng)上有很多代理IP提供商,我們可以通過購買代理IP解決被封IP的問題。這里,我們使用的是免費的站大爺代理ip(https://www.zdaye.com/)提供的免費IP。
在站大爺代理ip網(wǎng)站上,我們可以獲得如下信息:
- IP地址
- 端口號
- 區(qū)域
- 匿名度
- 類型
- 存活時間
- 驗證時間
我們需要使用的是IP地址和端口號,將它們加入到請求頭中,即可使用代理IP進行數(shù)據(jù)爬取。
2.使用代理IP
使用代理IP的方式非常簡單,只需要將代理IP加入到請求頭中即可。例如,以下代碼使用站大爺代理提供的代理IP進行數(shù)據(jù)爬?。?/p>
import requests
url = 'http://www.zuihaodaxue.com/ARWU2020.html'
proxies = {'http': 'http://111.177.190.36:9999', 'https': 'https://111.177.190.36:9999'}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get(url, headers=headers, proxies=proxies)
print(response.text)
這里我們設(shè)置了一個代理IP,格式為http://IP:port。在發(fā)送請求時,通過proxies參數(shù)將代理IP加入到請求頭中,即可使用代理IP進行數(shù)據(jù)爬取。
四、使用Flask框架實現(xiàn)輿情監(jiān)控可視化系統(tǒng)
Flask是一個輕量級的Python Web框架,用于編寫基于Web的應(yīng)用程序。它非常適合小型應(yīng)用程序和簡單的Web服務(wù),同時也可以作為基于大型應(yīng)用程序的核心。
Flask框架包含了請求分發(fā)、模板渲染、數(shù)據(jù)存取等功能,非常適合開發(fā)Web應(yīng)用程序和API。
在使用Flask框架搭建輿情監(jiān)控可視化系統(tǒng)時,我們需要安裝Flask和pymongo(用于連接MongoDB數(shù)據(jù)庫)庫,并使用以下代碼創(chuàng)建Flask應(yīng)用程序:
import json
from flask import Flask, render_template
from pymongo import MongoClient
app = Flask(__name__)
@app.route('/')
def index():
? ? client = MongoClient('localhost', 27017)
? ? db = client['university']
? ? collection = db['ARWU']
? ? data_list = []
? ? for data in collection.find():
? ? ? ? del data['_id']
? ? ? ? data_list.append(data)
? ? return render_template('index.html', data_list=json.dumps(data_list, ensure_ascii=False))
if __name__ == '__main__':
? ? app.run()
其中,localhost代表MongoDB數(shù)據(jù)庫所在的主機名,27017代表MongoDB數(shù)據(jù)庫的端口號。此外,我們也可以使用request庫獲取前端傳輸來的數(shù)據(jù),例如:
from flask import request
@app.route('/api/search', methods=['GET'])
def search():
? ? keyword = request.args.get('keyword')
? ? client = MongoClient('localhost', 27017)
? ? db = client['university']
? ? collection = db['ARWU']
? ? data_list = []
? ? for data in collection.find({'name': {'$regex': keyword}}):
? ? ? ? del data['_id']
? ? ? ? data_list.append(data)
? ? return json.dumps(data_list, ensure_ascii=False)
在使用Flask框架時,我們需要創(chuàng)建一個templates文件夾,用于存放html文件,如下所示:
在templates文件夾中,我們需要創(chuàng)建一個index.html文件,用于顯示數(shù)據(jù)。具體代碼如下:
<!DOCTYPE html>
<html>
<head>
? ? <meta charset="UTF-8">
? ? <title>中國大學(xué)排名</title>
? ? <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
? ? <style>
? ? ? ? /* 設(shè)置容器大小 */
? ? ? ? #main {
? ? ? ? ? ? height: 600px;
? ? ? ? }
? ? </style>
</head>
<body>
<!-- 設(shè)置一個容器用于展示數(shù)據(jù) -->
<div id="main"></div>
<!-- 使用JavaScript渲染表格 -->
<script type="text/javascript">
? ? // 獲取后端傳輸?shù)臄?shù)據(jù)
? ? var data = JSON.parse({{data_list}});
? ? // 初始化echarts圖表
? ? var myChart = echarts.init(document.getElementById('main'));
? ? // 配置圖表參數(shù)
? ? var option = {
? ? ? ? tooltip: {},
? ? ? ? legend: {
? ? ? ? ? ? data: ['總分']
? ? ? ? },
? ? ? ? xAxis: {
? ? ? ? ? ? data: data.map(function (item) {
? ? ? ? ? ? ? ? return item.name;
? ? ? ? ? ? })
? ? ? ? },
? ? ? ? yAxis: {},
? ? ? ? series: [{
? ? ? ? ? ? name: '總分',
? ? ? ? ? ? type: 'bar',
? ? ? ? ? ? data: data.map(function (item) {
? ? ? ? ? ? ? ? return item.score;
? ? ? ? ? ? })
? ? ? ? }]
? ? };
? ? // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。
? ? myChart.setOption(option);
</script>
</body>
</html>
這里,我們使用了ECharts庫(https://echarts.apache.org/)來實現(xiàn)數(shù)據(jù)可視化展示。最后,在命令行中運行app.py文件,即可啟動Flask應(yīng)用程序。
五、使用MongoDB存儲數(shù)據(jù)
在本例中,我們使用MongoDB作為數(shù)據(jù)存儲方式。MongoDB是一種非關(guān)系型數(shù)據(jù)庫,與關(guān)系型數(shù)據(jù)庫相比,MongoDB更加靈活、擴展性更好、支持海量數(shù)據(jù)存儲等特點。
在Python中,我們可以使用pymongo庫來進行MongoDB的連接和操作。具體代碼如下:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['university']
collection = db['ARWU']
data = {'rank': '1', 'name': 'Harvard University', 'region': 'USA', 'score': '100'}
collection.insert_one(data)
result = collection.find({'region': 'USA'})
for data in result:
? ? print(data)
在上述代碼中,我們首先連接MongoDB,并選擇要操作的數(shù)據(jù)庫和集合。然后,我們插入一條數(shù)據(jù),并通過find方法查詢指定條件的數(shù)據(jù)。
六、總結(jié)
本文介紹了如何使用Python爬取輿情數(shù)據(jù),通過使用代理IP提高數(shù)據(jù)爬取效率。同時,我們還學(xué)習(xí)了如何使用Flask框架搭建輿情監(jiān)控可視化系統(tǒng),以及使用MongoDB存儲數(shù)據(jù)。
這個輿情監(jiān)控可視化系統(tǒng)還有許多需要完善和改進的地方,例如如何實時更新數(shù)據(jù)、如何提高數(shù)據(jù)可視化展示的交互性等等,希望讀者能夠在此基礎(chǔ)上進行更進一步的探索和實踐。文章來源:http://www.zghlxwxcb.cn/news/detail-731783.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-731783.html
到了這里,關(guān)于Python基于Flask的高校輿情分析,輿情監(jiān)控可視化系統(tǒng)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!