python爬取天气数据 字典转换json报错怎么解决

Isabel439 2024-04-12 17:04:24
import requests
from bs4 import BeautifulSoup
import json
def getProvCityInfo():
    url='https://j.i8tq.com/weather2020/search/city.js'
    response=requests.get(url)
    content=response.content.decode('utf-8',errors='ignore')
   
    cityData=content[len('var city_data='):-1]
    cityData=json.loads(cityData)
  
    cityInfo={}
    for prov in cityData.keys():
        for city in cityData[prov].keys():
            for district in cityData[prov][city].keys():
                id=cityData[prov][city][district]['AREAID']
                name=cityData[prov][city][district]['NAMECN']
                cityInfo[name]=str(id)
    print(cityInfo)
    return cityInfo
def getCityInfo():
    while True:
        cityName=input("请输入待查询城市名字:")
        cityInfo=getProvCityInfo()
        cityCode=cityInfo.get(cityName,0)
        if cityCode==0:
            print("输入错误")
        else:
            break
    return cityName,cityCode

cityName,cityCode=getCityInfo()

webiste='http://www.weather.com.cn/weather1d/'+cityCode+'.shtml'
print("城市连接为:",webiste)

response=response.get(webite)
html=response.content.decode("utf-8",errors="ignore")
soup=BeautifulSoup(html,"html.parser")
tem=soup.find('p',class_="tem").text
win=soup.find('p',class_="win").text

print("\n城市:"+cityName)
print("温度:"+tem.replace('\n',''))
print("风力:"+win.replace('\n',''))

 

...全文
449 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
五楼442 2024-04-13
  • 打赏
  • 举报
回复 1
在获取网页内容时,你使用了错误的变量名 response,应该改为 requests。

在拼接城市天气网址时,你错拼写了 website 变量名,应该改为 webiste。

最后两行中,你可能会遇到 NoneType 对象没有 text 属性的问题,可以添加判断条件,以避免报错。

下面是修正后的代码:

python

import requests
from bs4 import BeautifulSoup
import json

def getProvCityInfo():
url = 'https://j.i8tq.com/weather2020/search/city.js'
response = requests.get(url)
content = response.content.decode('utf-8', errors='ignore')

cityData = content[len('var city_data='):-1]
cityData = json.loads(cityData)

cityInfo = {}
for prov in cityData.keys():
    for city in cityData[prov].keys():
        for district in cityData[prov][city].keys():
            id = cityData[prov][city][district]['AREAID']
            name = cityData[prov][city][district]['NAMECN']
            cityInfo[name] = str(id)
print(cityInfo)
return cityInfo

def getCityInfo():
while True:
cityName = input("请输入待查询城市名字:")
cityInfo = getProvCityInfo()
cityCode = cityInfo.get(cityName, 0)
if cityCode == 0:
print("输入错误")
else:
break
return cityName, cityCode

cityName, cityCode = getCityInfo()

website = 'http://www.weather.com.cn/weather1d/' + cityCode + '.shtml'
print("城市链接为:", website)

response = requests.get(website) # 修正此处变量名
html = response.content.decode("utf-8", errors="ignore")
soup = BeautifulSoup(html, "html.parser")
tem = soup.find('p', class_="tem").text if soup.find('p', class_="tem") else "未获取到温度信息"
win = soup.find('p', class_="win").text if soup.find('p', class_="win") else "未获取到风力信息"

print("\n城市:" + cityName)
print("温度:" + tem.replace('\n', ''))
print("风力:" + win.replace('\n', ''))

这样修改后,代码应该可以正常运行了。

10,172

社区成员

发帖
与我相关
我的任务
社区描述
人生苦短,我用python
社区管理员
  • Python 学习者
  • 嗨学编程
  • 松鼠爱吃饼干
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

欢迎来到Python学习者们的社区,

 

本社区分享你需要的文章、问题解答、技术互助、学习资源、面试系列等等

 

欢迎你的加入,祝你学有所成~

试试用AI创作助手写篇文章吧