・2017/12/21
Raspberry Piで Python言語で urllibを使って HTTP通信で JSONを処理する方法、Python 2/3
(ラズパイの Python言語で urllibを使って HTTP通信で JSON APIを処理する方法、Python2、Python3に対応)
Tags: [Raspberry Pi], [電子工作]
● Raspberry Pi 3 Model Bを遂に購入
Raspberry Pi3 Model B RPI2 RPI3
大人気の CPUボードの Raspberry Piに WiFiと Bluetoothが搭載されたモデルが新発売となりました。
以前から Raspberry Pi 2を買おうかどうか迷っていましたが、Raspberry Pi 3 Model Bの発売を機に購入を決意してラズベリアンになる事にしました。
※ ラズパイの OS Raspbianはバージョンが上がる毎に過去の版と OSの内部の作りが変わり、過去に書かれた製作記事(例えば Raspbian Wheezyの時代の記事)がそのままではエラーが出たりして動かない事が有ります。
※ 当方のホームページのラズパイ記事は全て Raspberry Pi 3 Model Bと Raspbian Jessieの組み合わせで動作確認をしております。
(ただし、将来的に新しい Raspbian OSが出た場合に、当方の Raspbian Jessieを基にした内容がそのままでは動かない可能性が有ります。)
※ 2017/08/16から Raspbian OSは Raspbian Jessieから Raspbian Stretchに変わりました。
※ 2019/06/20から Raspbian OSは Raspbian Stretchから Raspbian Busterに変わりました。
Download Raspbian for Raspberry Pi
ちなみに、歴代のバージョンと名称は
Debian | コードネーム | 年月 | 備考 | (参考)Ubuntuでの該当名称 |
Debian 11 | Bullseye | 2021/08/14~ | 2021/11からラズパイにリリース | Focal Fossa 20.04 LTS ? |
Debian 10 | Buster | 2019/06/20~ | 2019/06からラズパイ4対応 | Bionic 18.04 LTS |
Debian 9 | Stretch | 2017/08/16~ | 2018/03からラズパイ3B+対応 | Xenial 16.04 LTS |
Debian 8 | Jessie | 2015~ | 2016/02からラズパイ3対応 | Trusty 14.04 LTS |
Debian 7 | Wheezy | 2013~2016 | | |
Debian 6.0 | Squeeze | 2011~2014 | | |
Debian GNU/Linux 5.0 | Lenny | 2009~2012 | | |
● Python言語で urllibを使って HTTP通信してみる
Python言語で urllibを使って HTTP通信を行ないます。
pi@raspberrypi:~ $ python -V
Python 2.7.13
先ずは、HTTP通信で JSONを取得するだけの処理を書きます。
nano http_test1.py
python http_test1.py
(Python 2.x系)
http_test1.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# urllib パッケージを使ってインターネット上のリソースを取得するには
# https://docs.python.org/ja/3.6/howto/urllib2.html
import urllib
import urllib2
# 19.2. json - JSON エンコーダおよびデコーダ
# https://docs.python.org/ja/3.6/library/json.html#module-json
import json
# お天気Webサービス(Livedoor Weather Web Service / LWWS)
# http://weather.livedoor.com/weather_hacks/webservice
url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040'
req = urllib2.Request(url)
response = urllib2.urlopen(req)
print('----')
print(response.getcode())
print(response.geturl())
print(response.info())
# the_page = response.read().decode("utf-8")
# jsonObject = json.loads(the_page, 'utf-8')
the_page = response.read()
jsonObject = json.loads(the_page)
print('----')
print(jsonObject['description']['text'])
print(jsonObject['description']['publicTime'])
実行結果
----
200
http://weather.livedoor.com/forecast/webservice/json/v1?city=400040
Server: nginx
Date: Wed, 20 Dec 2017 11:45:10 GMT
Content-Type: application/json; charset=utf-8
Transfer-Encoding: chunked
Connection: close
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Set-Cookie: ldsuid=CoIxjFo6TUY8lWzcsB9nAg==; expires=Tue, 20-Mar-18 11:45:10 GMT; path=/
----
九州北部地方は、高気圧に覆われて概ね晴れていますが、寒気の影響によ
り曇りで小雨が降っている所があります。
~略~
~略~
~略~
<天気変化等の留意点>
特記事項はなし。
2017-12-20T16:39:00+0900
無事に HTTP通信で JSONを取得できたので、Open JTalkの発話処理と合体します。
Open JTalkは文字列に改行が有るとそこで発話を終了してしまうので改行を文字列置換で取り除いています。
nano http_test2.py
python http_test2.py
http_test2.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# urllib パッケージを使ってインターネット上のリソースを取得するには
# https://docs.python.org/ja/3.6/howto/urllib2.html
import urllib
import urllib2
# 19.2. json - JSON エンコーダおよびデコーダ
# https://docs.python.org/ja/3.6/library/json.html#module-json
import json
import subprocess
# お天気Webサービス(Livedoor Weather Web Service / LWWS)
# http://weather.livedoor.com/weather_hacks/webservice
url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040'
req = urllib2.Request(url)
response = urllib2.urlopen(req)
print('----')
print(response.getcode())
print(response.geturl())
print(response.info())
# the_page = response.read().decode("utf-8")
# jsonObject = json.loads(the_page, 'utf-8')
the_page = response.read()
jsonObject = json.loads(the_page)
print('----')
# print(jsonObject['description']['text'])
# print(jsonObject['description']['publicTime'])
speechString = jsonObject['description']['text']
# 改行が有ると切れてしまうので改行を文字列置換で取り除く
speechString = speechString.replace("\n", "")
print(speechString)
command = "echo \"%s\"" % speechString
command += " | open_jtalk -x /var/lib/mecab/dic/open-jtalk/naist-jdic -m /usr/share/hts-voice/nitech-jp-atr503-m001/nitech_jp_atr503_m001.htsvoice -ow /dev/stdout"
command += " | aplay --quiet"
proc = subprocess.Popen(
command,
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
# 終了を待つ場合(同期する)はコメントを取る
proc.communicate()
● Python 3.x系は no module named 'urllib2'になる
ついでに、json.loads(the_page)で下記エラーも出る。
TypeError: the JSON object must be str, not 'bytes'
pi@raspberrypi:~ $ python3 -V
Python 3.5.3
pi@raspberrypi:~ $ python3 http_test1.py
Traceback (most recent call last):
File "http_test.py", line 7, in <module>
import urllib2
ImportError: No module named 'urllib2'
TypeError: the JSON object must be str, not 'bytes'
responseStr = response.read().decode('utf-8')
(Python 3.x系)
nano py3_http_test1.py
python3 py3_http_test1.py
py3_http_test1.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# urllib パッケージを使ってインターネット上のリソースを取得するには
# https://docs.python.org/ja/3.6/howto/urllib2.html
import urllib
import urllib.request
# 19.2. json - JSON エンコーダおよびデコーダ
# https://docs.python.org/ja/3.6/library/json.html#module-json
import json
# お天気Webサービス(Livedoor Weather Web Service / LWWS)
# http://weather.livedoor.com/weather_hacks/webservice
url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040'
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
print('----')
print(response.getcode())
print(response.geturl())
print(response.info())
# the_page = response.read().decode("utf-8")
# jsonObject = json.loads(the_page, 'utf-8')
# TypeError: the JSON object must be str, not 'bytes'
the_page = response.read().decode('utf-8')
jsonObject = json.loads(the_page)
print('----')
print(jsonObject['description']['text'])
print(jsonObject['description']['publicTime'])
(Python 3.x系)
nano py3_http_test2.py
python3 py3_http_test2.py
py3_http_test2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# urllib パッケージを使ってインターネット上のリソースを取得するには
# https://docs.python.org/ja/3.6/howto/urllib2.html
import urllib
import urllib.request
# 19.2. json - JSON エンコーダおよびデコーダ
# https://docs.python.org/ja/3.6/library/json.html#module-json
import json
import subprocess
# お天気Webサービス(Livedoor Weather Web Service / LWWS)
# http://weather.livedoor.com/weather_hacks/webservice
url = 'http://weather.livedoor.com/forecast/webservice/json/v1?city=400040'
req = urllib.request.Request(url)
response = urllib.request.urlopen(req)
print('----')
print(response.getcode())
print(response.geturl())
print(response.info())
# the_page = response.read().decode("utf-8")
# jsonObject = json.loads(the_page, 'utf-8')
# TypeError: the JSON object must be str, not 'bytes'
the_page = response.read().decode('utf-8')
jsonObject = json.loads(the_page)
print('----')
speechString = jsonObject['description']['text']
# 改行が有ると切れてしまうので改行を文字列置換で取り除く
speechString = speechString.replace("\n", "")
print(speechString)
command = "echo \"%s\"" % speechString
command += " | open_jtalk -x /var/lib/mecab/dic/open-jtalk/naist-jdic -m /usr/share/hts-voice/nitech-jp-atr503-m001/nitech_jp_atr503_m001.htsvoice -ow /dev/stdout"
command += " | aplay --quiet"
proc = subprocess.Popen(
command,
shell = True,
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
# 終了を待つ場合(同期する)はコメントを取る
proc.communicate()
Tags: [Raspberry Pi], [電子工作]
●関連するコンテンツ(この記事を読んだ人は、次の記事も読んでいます)
FWinSdCardImager SDカード イメージ書き込みアプリ、ラズパイの Raspbian OS、Jetson Nanoの Ubuntuの書き込みに便利
ラズパイや Jetson Nano等のワンボードマイコン等への OSイメージの書き込みが簡単にできる
FWinPiFinder ラズベリーパイ IPアドレス発見アプリ。ARPコマンドでラズパイの IPアドレスを探索発見する
Raspberry Piや NVIDIA Jetson Nano等の IPアドレスを MACアドレスの OUI部分を使用して発見する
Raspberry Pi 3系のトラブルであるある第一位の電源トラブル、低電圧警報に関する情報のまとめ
ラズパイ3B系での低電圧警報に関する情報まとめ、コマンドラインやログファイルから低電圧を検知する方法
Raspberry Piで CPUの脆弱性 Spectreと Meltdownの脆弱性をチェックする方法
ラズパイで 2018年初頭に大騒ぎになったスペクターとメルトダウンの CPUの脆弱性をチェックする方法
Raspberry Pi Zero Wを海外通販の Pimoroni等での購入方法、購入できる通販ショップ一覧まとめ
ラズパイゼロW ワイヤレスモデルを海外通販でサクッと簡単に個人輸入で入手。技適通過でも国内販売は常に品切れ
Raspberry Pi 3で安定して使える相性の無い最適な microSDカードの種類のまとめ
ラズパイ3で安定して使える microSDカードを購入する Teamと SanDiskは絶対に買わない
Raspberry Pi 3 Model Bに専用カメラモジュール RaspiCamを接続する方法
ラズパイに専用カメラモジュールを接続して Raspbianで写真の静止画撮影や動画を録画する方法
Raspberry Pi 3の Linuxコンソール上で使用する各種コマンドまとめ
ラズパイの Raspbian OSのコマンドラインで使用する便利コマンド、負荷試験や CPUシリアル番号の確認方法等も
Raspberry Pi 3公式フォーラムの FAQの内容の日本語訳
ラズパイ公式フォーラムの「The Raspberry Pi 3 Model B Q&A thread」の日本語訳
Raspberry Pi 3で GPIO端子の I2C機能を有効化する方法
ラズパイ3の GPIO端子の I2C機能を有効にして各種センサーを繋げる方法まとめ
大人気の CPUボード、Raspberry Pi 3 Model Bで作ってみよう
Raspberry Piの開発環境の構築やタッチパネル付き液晶ディスプレイや各種センサーの使い方まとめ
Raspberry Pi関連はこちらへまとめました
下記以外にも多数のラズパイ関係の記事が有ります。
(I2C制御、GPIO制御、1-Wire制御、シリアル通信、日本語音声合成、日本語音声認識、中国語音声合成、MeCab 形態素解析エンジン、赤外線リモコン制御、秋月 I2C液晶モジュール、KeDei 3.5インチ液晶、HDMI 5インチ液晶、NFCカードリーダ、コマンドライン操作方法等)
Espressif ESP8266 Arduino互換でスケッチが使える ESP-12Eモジュール基板
Espressif ESP8266 ESP-12-E NodeMCU V1 ESP12 CP2102
BangGood通販はドローン以外にも面白い商品がまだまだ有った(電子工作編)
レーザー彫刻機、カラー液晶の DIYオシロ、Arduinoや Raspberry Pi用の小型カラー液晶
[HOME]
|
[BACK]
リンクフリー(連絡不要、ただしトップページ以外は Web構成の変更で移動する場合があります)
Copyright (c)
2017 FREE WING,Y.Sakamoto
Powered by 猫屋敷工房 & HTML Generator
http://www.neko.ne.jp/~freewing/raspberry_pi/raspberry_pi_python_http_urllib/