python 绘制指定城市周边景点7日内天气温度图表

1.引入 pyecharms

2.绘制line 图

3.数据保存在html中,方便查看

4.代码

-- coding: utf-8 --

“”"
Created on Sun Nov 27 11:20:53 2022

@author: niuzhen
“”"

import requests
import json
import pyecharts.options as opts
from bs4 import BeautifulSoup
from pyecharts.charts import Line
from pyecharts.faker import Faker
#根据js文件获取城市对应的编码
def getCityCode():
website=‘https://j.i8tq.com/weather2020/search/city.js’#城市编码数据的URL
respone=requests.get(website)
content=respone.content.decode(‘utf-8’)
#print(‘\n 页面返回的数据类型是:’,type(content))
cityData=content[len(‘var city_data =’):-1]#切片,去除多余的字符串头部
#print(cityData)
cityData=json.loads(cityData)#将字符串数据转换为字典
#print(“\n获取到的数据是:{}\n”,cityData)
cityCode={}
#根据字典特点,依次获取每个城市各地区的编码
for prov in cityData.keys():
for city in cityData[prov].keys():
for distinct in cityData[prov][city].keys():
id=cityData[prov][city][distinct][‘AREAID’]
name=cityData[prov][city][distinct][‘NAMECN’]
cityCode[name]=str(id)
return cityCode
#cityCode=getCityCode()
#print(cityCode)
#获取用户输入的城市名称
def getCityName():
while True:
cityName=input(“请输入您要查询天气的城市名称:”)
cityCode=getCityCode()
cityNum=cityCode.get(cityName,0)
if cityNum==0:
print(“您输入的地区名称不存在,请查证后重新输入!\n”)
else:
#print(str(cityNum))
break
return cityName,cityNum
#构造城市天气的URL
def getWeatherURl():
cityName,cityNum=getCityName()#获取城市对应的编号
website=‘http://www.weather.com.cn/weather1d/’+cityNum+‘.shtml’
return cityName,website
def getCityWeatherInfo():
cityName,url=getWeatherURl()
response=requests.get(url)
html=response.content.decode(‘utf-8’)

soup=BeautifulSoup(html,“html.parser”)

weather=soup.find(‘p’,class_=‘wea’).text
temp=soup.find(‘p’,class_=‘tem’).text
sky=soup.find(‘div’,class_=‘sky’).find(‘span’).text
print(cityName+“:天气”+weather+“,气温”+temp.replace(‘\n’,’ ‘)+’,‘+sky.replace(’\n’,‘’))

return cityName,url

#getCityWeatherInfo()
#获取目标城市周边景点的名称及对应链接
def getViewsWeather(name,url):
response=requests.get(url) #打开目标网页
html=response.content.decode(‘utf-8’) #读取页面html数据
soup=BeautifulSoup(html,‘html.parser’)
content=soup.find(‘div’,class_=‘t’)
date=content.find(‘h1’).text

tem=soup.find(‘p’,class_=‘tem’).text.replace(‘\n’,‘’)
wea=content.find(‘p’,class_=‘wea’).text.replace(‘\n’,‘’)
print(name+“:”+date+‘,’+tem+‘,’+wea)

def getViewNameLink(url):
try:
respone=requests.get(url)
html=respone.content.decode(‘utf-8’)
soup=BeautifulSoup(html,‘html.parser’)
content=soup.find(‘ul’,class_=‘clearfix view’)
content=content.find_all(‘li’)
except:
print(‘该地区周边景点的天气暂时无法查询!’)
return
#print(content)
viewInfo={}
#依次获取周边景点的名称及对应链接
for i in range(len(content)):
name=content[i].find(‘span’).text
link=content[i].find(‘a’).get(‘href’).replace(“#around2”,‘’)
link = link.replace(“weather1d”, “weather”)
viewInfo[name]=link
return viewInfo
#获取当前景点7天天气数据
def getViews7Data(link):
response=requests.get(link)#打开目标网页
#print(“当前的link是:”+link)
html=response.content.decode(‘utf-8’)#读取页面html数据
soup=BeautifulSoup(html,“html.parser”)
content=soup.find(“ul”,class_=“t clearfix”)
#print(str(content))
lis=content.find_all(“li”)
#print(str(lis))

dates=[]
viewsMaxTem=[]
for li in lis:
try:
date=li.find(‘h1’).text #获取当前日期
dates.append(date)#分析数据后去除多余字符,加入日期列表
tem=li.find(‘p’,class_=“tem”).find(‘span’).text #获取最高温度
viewsMaxTem.append(tem)
except Exception as err:
print(err)
return viewsMaxTem,dates #返回存有景点7天温度数据的字典,以及对应的日期

def drawLineBase(cityName,viewsData,dates):
viewsName=[]#用于后续存储各景点的名称
viewsTem=[]#用于后续存储各景点7天的温度数据
for key,value in viewsData.items():
viewsName.append(key)#提取景点名称,存入列表
viewsTem.append(value)#提取最高气温,存入列表
c=Line()#提前生成一个Line对象
c.add_xaxis(dates)#使用日期dates列表,添加X坐标数据
for i in range(len(viewsData)):#根据景点个数控制循环次数
c.add_yaxis(viewsName[i],viewsTem[i])#依次根据景点温度数据,绘制多条Y轴折线#设置图形标题#设置标题纵向位置为最低端 #设置标题横向位置为居中 #y轴最小刻度为特殊值‘dataMin’,则y周的最小值会取当前温度数值中最小值
c.set_global_opts(title_opts=opts.TitleOpts(title=cityName+“周边景点7天的最高气温”,pos_bottom=‘bottom’,pos_left=‘center’),yaxis_opts=opts.AxisOpts(min_=‘dataMin’),)

c.render(“周边景点温度.html”)#将绘制的图形在当前文件夹中生成一个HTML文件,在浏览器中查看

c.render(request,‘index.html’, {‘foo’: ‘bar’,}, content_type=‘application/xhtml+xml’)

c.render_notebook()

print(“zhixingdaozheli”)
‘’’
print(viewsData)
print(dates)
print(viewsTem)
print(viewsName)
‘’’

def main():
cityName,cityWebSite=getCityWeatherInfo()
viewInfo=getViewNameLink(cityWebSite)#获取当前城市周边景点名称及对应页面链接
#print(type(viewInfo))
#print(viewInfo)

viewsData={}#用于存储景点7天的天气数据,每一个元素是一个字典
viewsTem=[]#用于接收返回的景点名称及温度数据的字典数据
dates=[] # 用于接收返回的七天日期

for name,link in viewInfo.items():
viewsTem,dates=getViews7Data(link)#查询城市周边各景点天气
#print(viewsData)
#print(dates)
viewsData[name]=viewsTem#将当前景点及其气温数据存入字典,备用
print(“{}7天最高温度:{}”.format(name,viewsTem))#观察景点数据抓取结果

print(viewsData)

drawLineBase(cityName,viewsData,dates)#调用绘制折线图函数
main() #调用main函数

5.运行结果

请输入您要查询天气的城市名称:太原
太原:天气多云,气温 9°C ,天空淡蓝
汾河湿地公园7天最高温度:[‘10’, ‘7’, ‘-1’, ‘-1’, ‘1’, ‘3’, ‘5’]
森林公园西门7天最高温度:[‘9’, ‘6’, ‘-2’, ‘-2’, ‘0’, ‘2’, ‘4’]
晋祠公园7天最高温度:[‘9’, ‘6’, ‘-2’, ‘-2’, ‘0’, ‘2’, ‘4’]
中国煤炭博物馆7天最高温度:[‘10’, ‘6’, ‘-2’, ‘-2’, ‘0’, ‘2’, ‘4’]
太原动物园7天最高温度:[‘10’, ‘6’, ‘-2’, ‘-3’, ‘0’, ‘2’, ‘4’]
zhixingdaozheli

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值