简体   繁体   中英

python Traceback Keyerror using beautifulsoup

I have an error in my python code:

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()

The error is:

Traceback (most recent call last):

File "C:/Users/user/Desktop/untitled0.py", line 60, in main()

File "C:/Users/user/Desktop/untitled0.py", line 55, in main display(result)

File "C:/Users/user/Desktop/untitled0.py", line 20, in display print ('Condition: ' + result['cond'])

KeyError: 'cond'

Why is this error appearing?


My python version is 3.5.

None of your conditions evaluate to True so you never create the cond key in your dict, you are also going the wrong way about parsing, use the classes to get the data you want:

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)

If we run the code we get:

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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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