GAE(Python)でYahoo!知恵袋APIを叩いてXMLをパースする

PHPでYahoo!知恵袋APIを叩く方法は先日書いたので、今度はPythonで。しかもGAEを使ってみようかと。

# -*- coding: utf-8 -*-

from django.http import *
from django.shortcuts import render_to_response
from google.appengine.api import urlfetch
from xml.dom import minidom
import logging
import urllib

def index(request):

_url = “http://chiebukuro.yahooapis.jp/Chiebukuro/V1/questionSearch?appid=「自分で取得するアプリID」&query=”+ urllib.quote(‘焼肉’)
_result = urlfetch.fetch(_url)
_dom = minidom.parseString(_result.content)
_list = _dom.getElementsByTagName(“Question”)

for item in _list:

logging.info(u”ID:%srn” % item.getElementsByTagName(‘Id’)[0].firstChild.data)
logging.info(u”質問:%srn” % item.getElementsByTagName(‘Content’)[0].firstChild.data)
logging.info(u”回答:%srn” % item.getElementsByTagName(‘BestAnswer’)[0].firstChild.data)

return render_to_response(‘index.html’)

まぁ、これだけなんです。あ、Django使ってます。が、その部分は関係ないですね。XMLのパースはもうちっとスマートにならないかなあ。これはモジュールを知らないだけかなぁ。

ちなみに、BestAnswerがないと、というか、ノードに値がないとエラーが出ます。ので、実際に使う場合はその判定が必要になりますね。