目次

目次

PythonのRequestsを使ってレスポンスが化けたときの対応

アバター画像
福山
アバター画像
福山
最終更新日2017/01/10 投稿日2017/01/10

背景

import requests

url = 'http://www.ekidata.jp/api/s/1130205.xml'

r = requests.get(url)
print(r.text)
<?xml version="1.0" encoding="UTF-8"?>
<ekidata version="ekidata.jp station api 1.0">
    <station>
        <pref_cd>13</pref_cd>
        <line_cd>11302</line_cd>
        <line_name>JR山手線</line_name>
        <station_cd>1130205</station_cd>
        <station_g_cd>1130205</station_g_cd>
        <station_name>渋谷</station_name>
        <lon>139.701238</lon>
        <lat>35.658871</lat>
    </station>
</ekidata>

化けたので解決しました。

今回は、例として駅データ.jpを使用します。

コード

import requests

url = 'http://www.ekidata.jp/api/s/1130205.xml'

r = requests.get(url)
r.encoding = r.apparent_encoding
print(r.text)
import requests

url = 'http://www.ekidata.jp/api/s/1130205.xml'

r = requests.get(url)
print(r.content.decode('utf-8'))
<?xml version="1.0" encoding="UTF-8"?>
<ekidata version="ekidata.jp station api 1.0">
    <station>
        <pref_cd>13</pref_cd>
        <line_cd>11302</line_cd>
        <line_name>JR山手線</line_name>
        <station_cd>1130205</station_cd>
        <station_g_cd>1130205</station_g_cd>
        <station_name>渋谷</station_name>
        <lon>139.701238</lon>
        <lat>35.658871</lat>
    </station>
</ekidata>
アバター画像

福山

最近技術触れてないかも

目次