2 回答

TA貢獻1830條經(jīng)驗 獲得超3個贊
對您的代碼的(不雅)修復(fù)是:
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
# In find/findall, prefix namespaced tags with the full namespace in braces
for url in root.findall('{http://www.sitemaps.org/schemas/sitemap/0.9}url'):
loc = url.find('{http://www.sitemaps.org/schemas/sitemap/0.9}loc').text
print(loc)
這是因為您必須使用定義 XML 的命名空間來限定標記名稱。有關(guān)如何使用名稱空間find和findall方法的詳細信息來自Parse XML namespace with Element Tree findall

TA貢獻1803條經(jīng)驗 獲得超3個贊
如果你不想弄亂命名空間,這是比公認的答案更簡單的解決方案,而且更優(yōu)雅,使用通用的 xpath 查詢:
import lxml.etree
tree = lxml.etree.parse('test.xml')
for url in tree.xpath("//*[local-name()='loc']/text()"):
print(url)
如果你更喜歡使用 xml 命名空間,你應(yīng)該這樣做:
import lxml.etree
tree = lxml.etree.parse('test.xml')
namespaces = {
'sitemapindex': 'http://www.sitemaps.org/schemas/sitemap/0.9',
}
for url in tree.xpath("//sitemapindex:loc/text()", namespaces=namespaces):
print(url)
如果你更喜歡直接從內(nèi)存而不是文件加載 xml 數(shù)據(jù),你可以使用 lxml.etree.fromstring 而不是 lxml.etree.parse。
添加回答
舉報