Python-100-Days之 数据分析 Day67 番剧数据可视化

Day67 数据可视化之调用API并可视化
API:类似接口,在后端的数据可以通过API传递给前端,前端可以实现数据的可视化。与HTTP网页爬虫相比,API接口已经存储好数据,不太需要去解析网页。

参考文章:https://blog.csdn.net/qq_44332894/article/details/109862654
https://blog.csdn.net/weixin_43944997/article/details/105502469 https://www.liaoxuefeng.com/wiki/1016959663602400/1017639890281664

先用bilibili番剧进行数据提取
选用番剧列表2020年会员专享番,提取一页再进行可视化。

import requests                                                                                                                                                                                                             
import re                                                                                                                                                                                                                   
import pygal                                                                                                                                                                                                                
from pygal.style import LightColorizedStyle as LCS                                                                                                                                                                          
from pygal.style import LightenStyle as LS                                                                                                                                                                                  
                                                                                                                                                                                                                            
"""B站2020年付费会员番剧索引页数据"""                                                                                                                                                                                                    
URL='https://api.bilibili.com/pgc/season/index/result?season_version=-1&area=-1&is_finish=-1&copyright=-1&season_status=-1&season_month=-1&year=-1&style_id=-1&order=3&st=1&sort=0&page=1&season_type=1&pagesize=20&type=1' 
r=requests.get(URL)                                                                                                                                                                                                         
print("Status code:",r.status_code)                                                                                                                                                                                         
response_dict=r.json()                                                                                                                                                                                                      
print(response_dict.keys())                                                                                                                                                                                                 
print("list",response_dict['data']['list'])  #字典列表                                                                                                                                                                          
repo_dicts=response_dict['data']['list']    

names,numb=[],[]                                                               
for repo_dict in repo_dicts:                                                   
    print("标志:",repo_dict['badge']) #独家还是会员专享                                  
    print("链接:",repo_dict['link'])    #视频观看链接                                  
    pop=re.findall('\d+\.\d*',repo_dict['order'])   #浮点型匹配                     
    if len(pop)==False:                                                        
        pop=re.findall(r'\d+',repo_dict['order'])  #为空列表,用整数匹配                 
    float_pop=float(pop[0])                                                    
    #追番人数,先从列表里取出字符串,再用正则表达式提取数字                                               
    print("追番人数:",float_pop)                                                   
    print("名字:",repo_dict['title'])  #番名                                       
    print("\n")                                                                
    names.append(repo_dict['title'])  #x轴                                      
    numb.append(float_pop)            #Y轴                                                                                                                                                                                                                      
                                                                                                                                                                                                                            

输出:

Status code: 200
dict_keys(['code', 'data', 'message'])
list [{
   'badge': '独家', 'badge_info': {
   'bg_color': '#00C0FF', 'bg_color_night': '#0B91BE', 'text': '独家'}, 'badge_type': 1, 'cover': 'http://i0.hdslb.com/bfs/bangumi/image/4179b4398bad6f92e876e352cae21be7b8ceb8bf.png', 'index_show': '全26话', 'is_finish': 1, 'link': 'https://www.bilibili.com/bangumi/play/ss26801', 'media_id': 22718131, 'order': '917.3万追番', 'order_type': 'fav_count', 'season_id': 26801, 'season_type': 1, 'title': '鬼灭之刃', 'title_icon': ''}, {
   'badge': '独家', 'badge_info': {
   'bg_color': '#00C0FF', 'bg_color_night': '#0B91BE', 'text': '独家'}, 'badge_type': 1, 'cover': 'http://i0.hdslb.com/bfs/bangumi/image/962b27ff452b5daf98038a10a6dad3c134916e7d.png', 'index_show': '更新至第22话', 'is_finish': 0, 'link': 'https://www.bilibili.com/bangumi/play/ss34004', 'media_id': 28229443, 'order': '783.3万追番', 'order_type': 'fav_count', 'season_id': 34004, 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是爬取天气数据并可视化的方法: 1. 爬取天气数据 ```python import requests from bs4 import BeautifulSoup import csv # 获取网页内容 url = 'http://www.weather.com.cn/weather/101010100.shtml' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser') # 获取城市名称 city = soup.select('.crumbs a')[2].text # 获取每天的天气信息 days = soup.select('.t .clearfix') data = [] for day in days: date = day.select('.day')[0].text high_temp = day.select('.tem span')[0].text low_temp = day.select('.tem i')[0].text weather = day.select('.wea')[0].text wind = day.select('.win')[0].text.strip() data.append([date, high_temp, low_temp, weather, wind]) # 将数据存储到csv文件中 with open(f'{city}.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['日期', '最高温', '最低温', '天气', '风向']) for row in data: writer.writerow(row) ``` 2. 可视化平均气温走势折线图 ```python import pandas as pd import matplotlib.pyplot as plt # 读取csv文件 df = pd.read_csv(f'{city}.csv', encoding='utf-8') # 计算平均温度 df['平均温度'] = (df['最高温'] + df['最低温']) / 2 # 绘制折线图 plt.plot(df['日期'], df['平均温度'], label=city) plt.legend() plt.xlabel('日期') plt.ylabel('平均气温') plt.title(f'{city}一年平均气温走势') plt.show() ``` 3. 统计各类天气的天数并绘制条形图 ```python # 统计各类天气的天数 weather_count = df['天气'].value_counts() # 计算适合旅游的城市指数 weather_index = weather_count['多云'] * 0.3 + weather_count['晴'] * 0.4 + weather_count['阴'] * 0.3 # 绘制条形图 weather_count.plot(kind='bar') plt.xlabel('天气') plt.ylabel('天数') plt.title(f'{city}各类天气的天数') plt.show() print(f'{city}的适合旅游的城市指数为:{weather_index}') ``` 4. 统计每个月的平均气温并绘制折线图 ```python # 将日期转换为月份 df['月份'] = pd.to_datetime(df['日期']).dt.month # 按月份分组计算平均气温 month_avg_temp = df.groupby('月份')['平均温度'].mean() # 绘制折线图 plt.plot(month_avg_temp.index, month_avg_temp.values, label=city) plt.legend() plt.xlabel('月份') plt.ylabel('平均气温') plt.title(f'{city}每个月的平均气温') plt.show() # 计算最适合旅游的月份 best_month = month_avg_temp.idxmax() print(f'{city}最适合旅游的月份是{best_month}月') ``` 5. 统计平均气温在18~25度,风力小于5级的天数并判断哪个城市更适合居住 ```python # 计算符合条件的天数 temp_count = ((df['最高温'] + df['最低温']) / 2).between(18, 25).sum() wind_count = (df['风向'].str.contains('微风')).sum() # 判断哪个城市更适合居住 if temp_count > wind_count: print(f'{city}更适合居住') else: print(f'{city2}更适合居住') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值