【问题标题】:python Traceback Keyerror using beautifulsouppython Traceback Keyerror 使用 beautifulsoup
【发布时间】:2016-06-06 09:35:04
【问题描述】:

我的 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 行,在 main 显示(结果)

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

KeyError: 'cond'

为什么会出现这个错误?


我的python版本是3.5。

【问题讨论】:

    标签: python python-2.7 python-3.x python-import python-3.5


    【解决方案1】:

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

    【讨论】:

    • 非常感谢!! :) 你是我的英雄!!哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2021-02-19
    • 2022-01-18
    • 1970-01-01
    • 2016-04-01
    • 2016-07-01
    相关资源
    最近更新 更多