python爬取天⽓数据的实例详解
就在前⼏天还是⼆⼗多度的舒适温度,今天⼀下⼦就变成了个位数,⼩编已经感受到冬天寒风的⽆情了。之前对获取天⽓都是数据上的搜集,做成了⼀个数据表后,对温度变化的感知并不直观。那么,我们能不能⽤python中的⽅法做⼀个天⽓数据分析的图形,帮助我们更直接的看出天⽓变化呢?
使⽤pygal绘图,使⽤该模块前需先安装pip install pygal,然后导⼊import pygal
bar = pygal.Line() # 创建折线图
bar.add('最低⽓温', lows) #添加两线的数据序列
bar.add('最⾼⽓温', highs) #注意lows和highs是int型的列表
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
bar.x_label_rotation = 45
bar.title = cityname+'未来七天⽓温⾛向图' #设置图形标题
bar.x_title = '⽇期' #x轴标题
bar.y_title = '⽓温(摄⽒度)' # y轴标题
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
最终⽣成的图形如下图所⽰,直观的显⽰了天⽓情况:
完整代码
import csv
import sys
quest
from bs4 import BeautifulSoup # 解析页⾯模块
import pygal
import cityinfo
cityname = input("请输⼊你想要查询天⽓的城市:")
if cityname in cityinfo.city:
citycode = cityinfo.city[cityname]
else:
url = '⾮常抱歉,⽹页⽆法访问' + citycode + '.shtml'
header = ("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36") # 设置头部信息http_handler = quest.HTTPHandler()
opener = quest.build_opener(http_handler) # 修改头部信息
opener.addheaders = [header]
request = quest.Request(url) # 制作请求
response = opener.open(request) # 得到应答包
html = ad() # 读取应答包
html = html.decode('utf-8') # 设置编码,否则会乱码
# 根据得到的页⾯信息进⾏初步筛选过滤
final = [] # 初始化⼀个列表保存数据
bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象
body = bs.body
data = body.find('div', {'id': '7d'})
print(type(data))
ul = data.find('ul')
li = ul.find_all('li')
# 爬取⾃⼰需要的数据
i = 0 # 控制爬取的天数
lows = [] # 保存低温
highs = [] # 保存⾼温
daytimes = [] # 保存⽇期
weathers = [] # 保存天⽓
for day in li: # 便利到的每⼀个li
if i < 7:
temp = [] # 临时存放每天的数据
date = day.find('h1').string # 得到⽇期
#print(date)
temp.append(date)
daytimes.append(date)
inf = day.find_all('p') # 遍历li下⾯的p标签有多个p需要使⽤find_all ⽽不是find
#print(inf[0].string) # 提取第⼀个p标签的值,即天⽓
temp.append(inf[0].string)
weathers.append(inf[0].string)
temlow = inf[1].find('i').string # 最低⽓温
if inf[1].find('span') is None: # 天⽓预报可能没有最⾼⽓温
temhigh = None
temperate = temlow
else:
temhigh = inf[1].find('span').string # 最⾼⽓温
temhigh = place('℃', '')
temperate = temhigh + '/' + temlow
# temp.append(temhigh)
# temp.append(temlow)
lowStr = ""
lowStr = lowStr.join(temlow.string)
lows.append(int(lowStr[:-1])) # 以上三⾏将低温NavigableString转成int类型并存⼊低温列表
if temhigh is None:
highs.append(int(lowStr[:-1]))
highStr = ""
highStr = highStr.join(temhigh)
highs.append(int(highStr)) # 以上三⾏将⾼温NavigableString转成int类型并存⼊⾼温列表
temp.append(temperate)
final.append(temp)
i = i + 1
# 将最终的获取的天⽓写⼊csv⽂件
with open('weather.csv', 'a', errors='ignore', newline='') as f:
f_csv = csv.writer(f)
f_csv.writerows([cityname])
f_csv.writerows(final)
# 绘图
bar = pygal.Line() # 创建折线图
bar.add('最低⽓温', lows)
bar.add('最⾼⽓温', highs)
bar.x_labels = daytimes
bar.x_labels_major = daytimes[::30]
# bar.show_minor_x_labels = False # 不显⽰X轴最⼩刻度
bar.x_label_rotation = 45
bar.title = cityname+'未来七天⽓温⾛向图'
bar.x_title = '⽇期'html特效代码天气时钟
bar.y_title = '⽓温(摄⽒度)'
bar.legend_at_bottom = True
bar.show_x_guides = False
bar.show_y_guides = True
Python爬取天⽓数据实例扩展:
import requests
from bs4 import BeautifulSoup
from pyecharts import Bar
ALL_DATA = []
def send_parse_urls(start_urls):
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36" }
for start_url in start_urls:
response = (start_url,headers=headers)
# 编码问题的解决
response = de("raw_unicode_escape").decode("utf-8")
soup = BeautifulSoup(response,"html5lib") #lxml解析器:性能⽐较好,html5lib:适合页⾯结构⽐较混乱的
div_tatall = soup.find("div",class_="conMidtab") #find() 符合要求的第⼀个元素
tables = div_tatall.find_all("table") #find_all() 到符合要求的所有元素的列表
for table in tables:
trs = table.find_all("tr")
info_trs = trs[2:]
for index,info_tr in enumerate(info_trs): # 枚举函数,可以获得索引
# print(index,info_tr)
# print("="*30)
city_td = info_tr.find_all("td")[0]
temp_td = info_tr.find_all("td")[6]
# if的判断的index的特殊情况应该在⼀般情况的后⾯,把之前的数据覆盖
if index==0:
city_td = info_tr.find_all("td")[1]
temp_td = info_tr.find_all("td")[7]
city=list(city_td.stripped_strings)[0]
temp=list(temp_td.stripped_strings)[0]
ALL_DATA.append({"city":city,"temp":temp})
return ALL_DATA
def get_start_urls():
start_urls = [
"www.weather/textFC/hb.shtml",
"www.weather/textFC/db.shtml",
"www.weather/textFC/hd.shtml",
"www.weather/textFC/hz.shtml",
"www.weather/textFC/hn.shtml",
"www.weather/textFC/xb.shtml",
"www.weather/textFC/xn.shtml",
"www.weather/textFC/gat.shtml",
]
return start_urls
def main():
"""
主程序逻辑
展⽰全国实时温度最低的⼗个城市⽓温排⾏榜的柱状图
"""
# 1 获取所有起始url
start_urls = get_start_urls()
# 2 发送请求获取响应、解析页⾯
data = send_parse_urls(start_urls)
# print(data)
# 4 数据可视化
#1排序
data.sort(key=lambda data:int(data["temp"]))
#2切⽚,选择出温度最低的⼗个城市和温度值
show_data = data[:10]
#3分出城市和温度
city = list(map(lambda data:data["city"],show_data))
temp = list(map(lambda data:int(data["temp"]),show_data))
#4创建柱状图、⽣成⽬标图
chart = Bar("中国最低⽓温排⾏榜") #需要安装pyechart模块
chart.add("",city,temp)
if __name__ == '__main__':
main()
到此这篇关于python爬取天⽓数据的实例详解的⽂章就介绍到这了,更多相关python爬⾍天⽓数据的分析内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论