我的python代码中有错误:
Dim D1 as Date = Now
Dim D2 as Date = D1.AddDays(10)
Dim difference As
TimeSpan = D2.Subtract(D1)
msgBox(“{0} Days”, difference.TotalDays) 'THIS WILL RETURN Total No. of Days
错误是:
追踪(最近一次呼叫最后一次):
文件" C:/Users/user/Desktop/untitled0.py" ;,第60行,在 main()的
文件" C:/Users/user/Desktop/untitled0.py",第55行,主要 显示器(结果)
文件" C:/Users/user/Desktop/untitled0.py",第20行,显示 打印('条件:' +结果[' cond'])
KeyError:' cond'
为什么会出现此错误?
我的python版本是3.5。
答案 0 :(得分:0)
你的条件都没有评估为True,所以你永远不会在你的dict中创建cond键,你也会采用错误的方式进行解析,使用类来获取你想要的数据:
def display(result):
print('Weather in Suwon, Asia at ' + strftime('%H:%M', localtime()) + '\n')
print('Condition: ' + result['cond'])
print('Temparature: ' + result['temp'])
print('RealFeel: ' + result["realfeel"])
print(result['humid'])
print(result['cloud'])
def main():
with urllib.request.urlopen("http://www.accuweather.com/en/kr/suwon/223670/current-weather/223670") as url:
html = url.read()
soup = BeautifulSoup(html, "lxml")
soup = soup.find('div', {'id': 'detail-now'})
result = {"realfeel": soup.select_one("span.realfeel").text.split(None, 1)[1],
"temp": soup.select_one("span.temp").text.strip(),
"cond": soup.select_one("span.cond").text.strip(),
"humid": soup.select_one("ul.stats li").text,
"cloud": soup.select_one("ul.stats li:nth-of-type(4)").text}
display(result)
如果我们运行代码,我们会得到:
In [2]: main()
Humidity: 68%
22°
Weather in Suwon, Asia at 11:17
Condition: Mostly cloudy
Temparature: 22°
RealFeel: 22°
Humidity: 68%
Cloud Cover: 95%