私は Python が初めてで、XML ファイルを HTML に変更するユーティリティに取り組んでいます。XML はrequest = urllib2.Request(url)
、コードの前半でカスタム URL を生成しresponse = urllib2.urlopen(request)
、最後にxml_response = response.read()
. 私が知る限り、これは問題なく動作します。
私の問題は、応答を解析することです。手始めに、返される XML 構造の部分的な例を次に示します。
ここの minidom チュートリアルのスライドショーの例を適応させて、私の XML (ちなみにこれは eBay の検索結果です) を解析しようとしました: http://docs.python.org/2/library/xml.dom.minidom.html
これまでの私のコードは、問題を診断する試みとして try ブロックを使用して、次のようになります。
doc = minidom.parseString(xml_response)
#Extract relevant information and prepare it for HTML formatting.
try:
handleDocument(doc)
except:
print "Failed to handle document!"
def getText(nodelist): #taken straight from slideshow example
rc = []
for node in nodelist:
if node.nodeType == node.TEXT_NODE:
print "A TEXT NODE!"
rc.append(node.data)
return ''.join(rc) #this is a string, right?
def handleDocument(doc):
outputFile = open("EbaySearchResults.html", "w")
outputFile.write("<html>\n")
outputFile.write("<body>\n")
try:
items = doc.getElementsByTagName("item")
except:
"Failed to get elements by tag name."
handleItems(items)
outputFile.write("</html>\n")
outputFile.write("</body>\n")
def handleItems(items):
for item in items:
title = item.getElementsByTagName("title")[0] #there should be only one title
print "<h2>%s</h2>" % getText(title.childNodes) #this works fine!
try: #none of these things work!
outputFile.write("<h2>%s</h2>" % getText(title.childNodes))
#outputFile.write("<h2>" + getText(title.childNodes) + "</h2>")
#str = getText(title.childNodes)
#outputFIle.write(string(str))
#outputFile.write(getText(title.childNodes))
except:
print "FAIL"
正しいタイトル テキストがコンソールに出力されるのに例外がスローされ、出力ファイルで機能しない理由がわかりません。このような単純な文字列を書くoutputFile.write("<html>\n")
とうまくいきます: 私の文字列構造はどうなっていますか? 私が知る限りgetText
、minidom の例で使用しているメソッドは文字列を返します。これは、ファイルに書き込むことができるようなものです..?