前提・実現したいこと
1週間ほど前にpythonを学びはじめた超初心者です。質問の内容におかしな点がありましたらご容赦くださいませ。
とある初心者向けのpythonの教本を見ながら、会話botプログラムを作成しています。
その中に、「お天気webサービス」というAPIを使用し、「天気」とコマンドを入れると東京の今日の天気を返してくれる機能を追加しました。
発生している問題・エラーメッセージ
プログラムを実行し、天気とコマンドを入れてみると、下記のようなエラーが出ました。
* 種類: <class 'json.decoder.JSONDecodeError'> * 内容 Expecting value: line 2 column 1 (char 4)
該当のソースコード
*pybot_weather.py(モジュール)
import requests def weather_command(): base_url = 'http://weather.livedoor.com/forecast/webservice/json/v1' city_code = '130010' url = '{}?city={}'.format(base_url, city_code) r = requests.get(url) weather_data = r.json() city = weather_data["location"]["city"] label = weather_data["forecasts"][0]["dateLabel"] telop = weather_data["forecasts"][0]["telop"] response = '{}ノ{}ノ天気ハ「{}」デス'.format(city, label, telop) return response
*pybot.py(会話botプログラム本体) while True:の中のif '天気'...という部分で、上のモジュールの関数を呼び出しています
from pybot_eto import eto_command from pybot_random import choice_command, dice_command from pybot_datetime import today_command, now_command, weekday_command from pybot_sqrt import sqrt_command from pybot_weather import weather_command def len_command(command): cmd, text = command.split() length = len(text) response = '文字列ノ長サハ {} 文字デス'.format(length) return response def heisei_command(command): heisei, year_str = command.split() if year_str.isdigit(): year = int(year_str) if year >= 1989: heisei_year = year - 1988 response = '西暦{}年ハ、平成{}年デス'.format(year, heisei_year) else: response = '西暦{}年ハ、平成デハアリマセン'.format(year) else: response = '数値ヲ指定シテクダサイ' return response command_file = open('pybot.txt', encoding='utf-8') raw_data = command_file.read() command_file.close() lines = raw_data.splitlines() bot_dict = {} for line in lines: word_list = line.split(',') key = word_list[0] response = word_list[1] bot_dict[key] = response while True: try: command = input('pybot>') response = '' for message in bot_dict: if message in command: response = bot_dict[message] break if '長さ' in command: response = len_command(command) if '平成' in command: response = heisei_command(command) if '干支' in command: response = eto_command(command) if '選ぶ' in command: response = choice_command(command) if 'サイコロ' in command: response = dice_command() if '今日' in command: response = today_command() if '現在' in command: response = now_command() if '曜日' in command: response = weekday_command(command) if '平方根' in command: response = sqrt_command(command) if '天気' in command: response = weather_command() if not response: response = '何ヲ言ッテルカ、ワカラナイ' print(response) if 'さようなら' in command: break except Exception as e: print('予期せぬエラーが発生しました') print('* 種類:', type(e)) print('* 内容', e)
試したこと
色々と調べていると、そもそもrequests.get(url)で得たお天気webサービスの結果がjson形式では無いためにjson.decoder.JSONDecodeErrorが出ているのではと考えるに至っております。
実際に、下記のようにレスポンスを確認すると
<!DOCTYPE html>...と始まる、html形式のtextが返ってきます。このコードも教本にあるのですが、教本ではこの時点でjson形式の文字列が返ってきています。import requests r = requests.get('http://weather.livedoor.com/forecast/webservice/json/v1?city=130010') print(r.status_code) print(r.text[:100])
色々と調べていてもこのAPIをしようしている場合はjson形式でレスポンスが返ってくるはずのようで、同じような問題を見つけられずにいます。
聞きたいことまとめ
お天気webサービスAPIをしようし、上記プログラムで天気コマンドを打った時に天気情報をえたい。どうやらAPIからのレスポンスがjson形式では無いらしく、エラーが出てしまう。どうすればjson形式で結果を得られるのかが知りたい。
どなたかわかる方いらっしゃいましたら、御助力のほどお願いいたします。
よろしくお願いいたします。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/08/14 15:52
退会済みユーザー
2020/08/14 15:54