python读取指定城市的天气

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 ,天空淡蓝

你可能感兴趣的:(python学习,python,开发语言)