【问题标题】:Python TypeError on executing weather service code执行天气服务代码时出现 Python TypeError
【发布时间】:2018-03-04 20:26:11
【问题描述】:

我正在使用天气 API 来设计一个使用 python 的 slack 机器人服务。

我的源代码是-

import requests
import re
import json
from bs4 import BeautifulSoup


def weather(cityname):
    cityid = extractid(cityname)
    url = "http://api.openweathermap.org/data/2.5/forecast?id=" + str(cityid) + "&APPID=c72f730d08a4ea1d121c8e25da7e4411"
    while True:
        r = requests.get(url, timeout=5)
        while r.status_code is not requests.codes.ok:
            r = requests.get(url, timeout=5)
        soup = BeautifulSoup(r.text)
        data = ("City: " + soup.city["name"] + ", Country: " + soup.country.text + "\nTemperature: " + soup.temperature["value"] +
    " Celsius\nWind: " + soup.speed["name"] + ", Direction: " + soup.direction["name"] + "\n\n" + soup.weather["value"])
    # print data
    return data


def extractid(cname):
    with open('/home/sourav/Git-Github/fabulous/fabulous/services/city.list.json') as data_file:
    data = json.load(data_file)
    for item in data:
        if item["name"] == cname:
            return item["id"]


def on_message(msg, server):
    text = msg.get("text", "")
    match = re.findall(r"~weather (.*)", text)
    if not match:
        return
    searchterm = match[0]
    return weather(searchterm.encode("utf8"))


on_bot_message = on_message

但是执行代码会出现以下错误-

 File "/usr/local/lib/python2.7/dist-packages/fabulous-0.0.1-py2.7.egg/fabulous/services/weather.py", line 19, in weather
" Celsius\nWind: " + soup.speed["name"] + ", Direction: " + soup.direction["name"] + "\n\n" + soup.weather["value"])
TypeError: 'NoneType' object has no attribute '__getitem__'

我无法弄清楚错误是什么。请帮忙!

【问题讨论】:

    标签: python json beautifulsoup


    【解决方案1】:

    __getitem__ 在您请求字典键时调用,例如 a['abc'] 转换为 a.__getitem__('abc')

    所以在这种情况下soup 的一个属性是Nonespeeddirectionweather

    确保您的 r.text 包含您想要的数据,只需打印即可:

    print(r.text)
    

    解析数据中的列表结构:

    for child in soup.findChildren():
        print child
    

    总是假设你的输入数据可能是错误的,而不是做soup.citysoup.find('city'),它可能是空的,所以:

    city = soup.find('city')
    if len(city):
       city_name = city[0]['name']
    else:
       city_name = 'Error' # or empty, or sth
    

    【讨论】:

    • 在这种情况下该怎么办...我是初学者,无法弄清楚
    • 更新答案、调试输入、打印汤解析数据等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 2020-05-05
    相关资源
    最近更新 更多