Найти - Пользователи
Полная версия: Парсинг xml
Начало » Python для новичков » Парсинг xml
1
wizard
Здравствуйте, помогите распарсить xml

<data>
<bot_ips>
<ip>77.91.226.131</ip>
<ip>77.91.226.130</ip>
<ip>86.111.22.107</ip>
<ip>88.208.19.9</ip>
<ip>77.91.226.135</ip>
<ip>77.91.226.133</ip>
<ip>77.91.226.151</ip>
<ip>206.161.193.2</ip>
<ip>207.226.178.210</ip>
<ip>77.91.226.180</ip>
<ip>77.91.228.36</ip>
<ip>77.91.226.136</ip>
</bot_ips>
<config>
<item name="after_text"></item>
<item name="delimiter">;</item>
<item name="before_text"></item>
<item name="end"><!--e63638c8--></item>
<item name="start"><!--e63638c8--></item>
</config>
<pages>
<page url="/tag/aqua_snezhok/">
<level>2</level>
<link>
<a href="http://ffff133.cn/" target="_blank">www.ffff133.cn</a>
</link>
</page>
<page url="/tag/%D0%A0%D0%B0%D0%B1%D0%BE%D1%82%D0%B0/">
<level>2</level>
<link>
<a href="http://ffff089.cn/" target="_blank">ppp</a>
</link>
</page>
</pages>
</data>
У меня получаеться вот такой код
from xml.etree import ElementTree as ET
import urllib

def find_text(element):
if element.text is None:
for subelement in element:
for txt in find_text(subelement):
yield txt

else:
yield element.text

feed = urllib.urlopen("http://127.0.0.1/DEFAULT.xml")
try:
tree = ET.parse(feed)

except Exception, inst:
print "Unexpected error opening %s: %s" % (tree, inst)

root = tree.getroot()

for txt in find_text(root):
print txt
Ferroman
А вопрос-то в чём?
wizard
сори, как переделать его так чтобы он выводил

/tag/aqua_snezhok/ 2 <a href="http://ffff133.cn/“ target=”_blank“>www.ffff133.cn</a>
/tag/%D0%A0%D0%B0%D0%B1%D0%BE%D1%82%D0%B0/ 2 <a href=”http://ffff089.cn/“ target=”_blank">ppp</a>
wizard
Разобрался :) всё оказалось очень просто

from xml.etree import ElementTree as ET

root = ET.parse('xml.xml).getroot()
for element in root.findall('pages/page/'):
print element.attrib["url"]
for link in element.findall('link/'):
print link.text
for level in element.findall('level/'):
print level.text
теперь остался вопрос, как сделать из %D0%A0%D0%B0%D0%B1%D0%BE%D1%82%D0%B0 сделать человеческий русский?
igor.kaist
import urllib
s='%D0%A0%D0%B0%D0%B1%D0%BE%D1%82%D0%B0'
print urllib.unquote(s)
wizard
igor.kaist
import urllib
s='%D0%A0%D0%B0%D0%B1%D0%BE%D1%82%D0%B0'
print urllib.unquote(s)
Спасибо большое, помогло.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB