繁体   English   中英

使用beautifulsoup的python Traceback Keyerror

[英]python Traceback Keyerror using beautifulsoup

我的python代码中有一个错误:

import urllib.request

from bs4 import BeautifulSoup

import traceback

from time import localtime, strftime

def display(result):      

        print ('Weather in Suwon, Asia at ' + strftime('%H:%M', localtime()) + '\n')
        print ('Condition: ' + result['cond'])
        print ('Temparature: ' + result['temp'] + u"\N{DEGREE SIGN}" + 'C')
        print ('RealFeel: ' + result['realfeel'] + u"\N{DEGREE SIGN}" + 'C')
        print (result['humid'])
        print (result['cloud'])
        print

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 = {}

    while soup:
        if soup.get('class') == 'cond':
            result['cond'] = soup.text
        elif soup.get('class') == 'temp':
            result['temp'] = soup.text.replace("°", "")
        elif soup.get('class') == 'realfeel':
            s = soup.text.replace("°", "")
            result['realfeel'] = s.replace("RealFeel® ", "")
        elif soup.get('cellspacing') == None and soup.get('class') == 'stats':
            ss = soup.findAll('li')
            for li in ss:
                if 'humid' in li.text:
                    result['humid'] = li.text.replace(":", ": ")
                elif 'Cloud' in li.text:
                    result['cloud'] = li.text.replace(":", ": ")
            break

        soup = soup.findNext()

    display(result)


if __name__ == "__main__":
    try:
        main()
    except:
        traceback.print_exc()

错误是:

Traceback(最近一次调用最后一次):

在主()中的文件“C:/Users/user/Desktop/untitled0.py”,第60行

在主显示中输入文件“C:/Users/user/Desktop/untitled0.py”,第55行(结果)

文件“C:/Users/user/Desktop/untitled0.py”,第20行,显示打印('条件:'+结果['cond'])

KeyError:'cond'

为什么会出现此错误?


我的python版本是3.5。

你的条件都没有评估为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%

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM