[問題] 如何用python抓取XML中的data (ETREE)
各位好
本人有類似以下的XML檔(output.xml)必須要用python來處理
希望可以擷取各個tag中的值
我的XML檔中有namespace,內容如下:
<data xmlns="urn:ietf:params:ns:netconf:base:1.0">
<interfaces xmlns="" rel="nofollow">http://namespace.net">
<interface>
<name>Interface0</name>
</interface>
<interface>
<name>Interface1</name>
</interface>
</interfaces>
</data>
查了一下網路,有xml.etree這個library可以用
以下是我的code
------------------------------------
from xml.etree import cElementTree as ET
tree = ET.ElementTree(file="output.xml")
root = tree.getroot()
nsmap = {'':'http://namespace.net'} # namespace
for name in root.iterfind('./interfaces/interface/name', namespaces=nsmap):
print(name.text)
-----------------------------------------
這個code是可以跑的,但自己希望可以進一步實現:
只抓取Interface1,也就是第二個interface中name的值
我嘗試過將'./interfaces/interface/name'改為'./interfaces/interface[2]/name'
不過這只有在XML中沒有namespace時,才能成功抓取到Interface1
請問各版友,有人知道對於有namespace的xml,如果有重複的tag
要如何只抓第k個tag中的值?
謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 108.254.89.199 (美國)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1645518657.A.11A.html
→
02/22 20:28,
3年前
, 1F
02/22 20:28, 1F
→
02/22 22:27,
3年前
, 2F
02/22 22:27, 2F
→
02/28 04:05, , 3F
02/28 04:05, 3F
推
03/09 17:47, , 4F
03/09 17:47, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):
Python 近期熱門文章
PTT數位生活區 即時熱門文章