python读取指定城市的天气

该博客展示了如何利用Python的requests、json和BeautifulSoup库获取城市天气信息。首先,从js文件中提取城市编码,然后根据用户输入的城市名称查询天气,并构造天气查询URL。最后,解析HTML页面获取天气、温度和天空状况等信息。
摘要由CSDN通过智能技术生成

1.import json ,使用json获取js文件的字典结构

2.使用BeautifulSoup获取天气页面的天气信息

3.代码:

import requests
import json
from bs4 import BeautifulSoup
#根据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]#切片,去除多余的字符串头部:‘var city_data =’
#print(cityData)
cityData=json.loads(cityData)#将字符串数据转换为字典,json.load()是用来读取文件的;json.loads()是用来读取字符串的
#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’,‘’))
getCityWeatherInfo()

4.运行结果:

请输入您要查询天气的城市名称:太原
太原:天气多云,气温 9°C ,天空淡蓝

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值