文章目录
爬取微博实时热搜数据可视化分析一、爬取数据1.1 Spider主要函数1.2 根据微博一分钟更新一次的状态进行爬虫
二、可视化2.1 利用轮播图加柱状图进行可视化
爬取微博实时热搜数据可视化分析
如今微博实时更新速度非常快,基于它每分钟更新一次热搜的情况,每分钟爬取一次信息,查看实时热搜的变动。
from fake_useragent import UserAgent # 反爬请求头
from bs4 import BeautifulSoup # BS4爬虫
from datetime import datetime # 时间处理模块
import time # 时间模块
import csv # csv模块
import requests # 爬取数据
import schedule # 定时调度模块
import pandas as pd # 数据处理
一、爬取数据
1.1 Spider主要函数
def main():
url = 'https://s.weibo.com/top/summary?cate=realtimehot&sudaref=s.weibo.com&display=0&retcode=6102'
agents = UserAgent()
headers = {'User-Agent': agents.random}
response = requests.get(url, headers=headers) # 响应数据
top_search_dict = {} # 建立字典保存数据
soup = BeautifulSoup(response.text, 'html.parser') # 解析数据
items = soup.find_all('td', class_='td-02') # 获取微博热搜数据
for item in items:
title = item.find('a').text.strip() # 获取标题
counts = item.find_all('span')
for i in counts:
top_search_dict[title] = i.get_text() # 获取热搜量
top_search_dict['date'] = datetime.now().strftime('%Y/%m/%d %H:%M') # 获取时间
with open('weibo_search.csv', 'a', encoding='gbk', newline='') as f: # 存入csv文件
w = csv.DictWriter(f, top_search_dict.keys())
w.writeheader()
w.writerow(top_search_dict)
1.2 根据微博一分钟更新一次的状态进行爬虫
# 自动运行爬虫一分钟一次
def auto_spider(stop_time):
schedule.every(1).minutes.do(main) # 设置每分钟进行一次调度
while True:
if datetime.now().strftime('%H:%M') |