ElementTree を使用して、XML の文字列内のタグと属性を検索しようとしています。文字列は次のとおりです。
'<?xml version="1.0" encoding="UTF-8" ?>\n<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01">\n\t<status success="true" statusCode="2000"/>\n\t<readCalls>\n\t<classify id="thing">\n\t\t<classification textCoverage="0">\n\t\t\t<class className="Astronomy" p="0.333333"/>\n\t\t\t<class className="Biology" p="0.333333"/>\n\t\t\t<class className="Mathematics" p="0.333333"/>\n\t\t</classification>\n\t</classify>\n\t</readCalls>\n</uclassify>'
美化:
<?xml version="1.0" encoding="UTF-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01">
<status success="true" statusCode="2000"/>
<readCalls>
<classify id="thing">
<classification textCoverage="0">
<class className="Astronomy" p="0.333333"/>
<class className="Biology" p="0.333333"/>
<class className="Mathematics" p="0.333333"/>
</classification>
</classify>
</readCalls>
</uclassify>
この小さなコードを使用して、文字列を検索可能な XML ツリーに変換しました。
>>> from xml.etree.ElementTree import fromstring, ElementTree
>>> tree = ElementTree(fromstring(a))
tree.find('uclassify')
usingはその要素/タグを返すと思っていましたが、何も返さないようです。私も試しました:
for i in tree.iter():
print i
何かを印刷しますが、私が望むものではありません:
<Element '{http://api.uclassify.com/1/ResponseSchema}uclassify' at 0x1011ec410>
<Element '{http://api.uclassify.com/1/ResponseSchema}status' at 0x1011ec390>
<Element '{http://api.uclassify.com/1/ResponseSchema}readCalls' at 0x1011ec450>
<Element '{http://api.uclassify.com/1/ResponseSchema}classify' at 0x1011ec490>
<Element '{http://api.uclassify.com/1/ResponseSchema}classification' at 0x1011ec4d0>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec510>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec550>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec590>
BeautifulSoup モジュールなどで、タグと属性を検索する最も簡単な方法は何ですか? たとえば、クラス要素の className 属性と p 属性を簡単に取得するにはどうすればよいでしょうか? lxml、xml.dom.minidom、および ElementTree についてさまざまなことを読み続けていますが、必要なものが得られないように見えるため、何かが欠けているに違いありません。