在处理具有默认名称空间的XML时,这是一个常见错误。您的XML具有默认的命名空间,在此声明为不带前缀的命名空间:
<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
请注意,除非另外声明(使用显式名称空间前缀或指向不同名称空间uri的本地默认名称空间),否则不仅声明了默认名称空间的元素在该名称空间中,而且所有后代元素都隐式继承祖先默认名称空间。这意味着,在这种情况下,包括在内的所有元素loc
都位于默认名称空间中。
要选择名称空间中的元素,您需要定义名称空间映射的前缀,并在XPath中正确使用该前缀:
from lxml import etree
str1 = '''<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<sitemap>
<loc>
http://www.example.org/sitemap_1.xml.gz
</loc>
<lastmod>2015-07-01</lastmod>
</sitemap>
</sitemapindex>'''
root = etree.fromstring(str1)
ns = {"d" : "http://www.sitemaps.org/schemas/sitemap/0.9"}
url = root.xpath("//d:loc", namespaces=ns)[0]
print etree.tostring(url)
<loc xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
http://www.example.org/sitemap_1.xml.gz
</loc>