[英]Parsing an XML file Python
作為一個相當新的Python學習者,我為自己設置了一個迷你項目來解析Highways England xml文件。 到目前為止,我的代碼是:
#!/usr/bin/python
import urllib2
varresponse = urllib2.urlopen('http://m.highwaysengland.co.uk/feeds/rss/AllEvents.xml')
from xml.etree import ElementTree as et
tree = et.parse(varresponse)
root = tree.getroot()
for item in root:
print(item.tag, item.attrib)
for author in root.iter('author')
print author
當我在終端中運行此命令時,它僅顯示單詞author,但如果需要的話,我希望它在author括號內顯示所有內容。 對我來說,下一步就是挑選關於M25的所有東西並打印出來,但是我也不完全知道該怎么做。
如果有人能給我任何改變的建議,我將非常感激,歡呼
如果只需要作者標簽內的電子郵件地址,請使用.text
例如:
for author in root.iter('author'):
print author.text
輸出:
info@highwaysengland.co.uk
info@highwaysengland.co.uk
info@highwaysengland.co.uk
info@highwaysengland.co.uk
如果要打印<author>
標記及其所有內容,請嘗試以下操作:
print et.tostring(author)
使用您的樣本輸入,將產生:
>>> print et.tostring(author)
<author>info@highwaysengland.co.uk</author>
如果只需要文本,則可以使用.text
屬性,如下所示:
print author.text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.