10,172
社区成员
发帖
与我相关
我的任务
分享
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',''))

在获取网页内容时,你使用了错误的变量名 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', ''))
这样修改后,代码应该可以正常运行了。