【问题标题】:How to use XPath in lxml python module [duplicate]如何在lxml python模块中使用XPath [重复]
【发布时间】:2016-07-05 17:33:55
【问题描述】:

我有一个如下的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
 <url>
  <loc>https://ezinearticles.com/</loc>
  <changefreq>hourly</changefreq>
  <priority>1.0</priority>
 </url>
 <url>
  <loc>https://ezinearticles.com/submit/</loc>
  <changefreq>weekly</changefreq>
  <priority>0.3</priority>
 </url>
 ...................

我想使用 xpathin lxml 模块从所有标签中获取 URL。我按照下面的代码实现了它,但它没有用。结果是空列表

from lxml import etree
parser = etree.XMLParser(ns_clean=True)
xmlfile = "sitemap1.xml"
xmlobj = etree.parse(xmlfile, parser)

loc = xmlobj.xpath('//loc[text()]')

print(loc)

谁能帮我修复我的脚本?

【问题讨论】:

  • ...当然,这个问题与 XHTML 无关,但它是完全相同的问题(只是有两个不同的命名空间)。

标签: python xml xpath xml-parsing lxml


【解决方案1】:
# define a namespace map
nsmap={'s': 'http://www.sitemaps.org/schemas/sitemap/0.9'}

# use it in your query
loc = xmlobj.xpath('//s:loc[text()]', namespaces=nsmap)

在您的原始代码中,您正在寻找 loc(在默认命名空间中),但该元素实际上是 {http://www.sitemaps.org/schemas/sitemap/0.9}loc(因为 xmlns= 意味着它下面的所有内容都默认使用该命名空间),这就是原始查询不匹配的原因。

【讨论】:

  • 尝试通过代码获取 "priority = 1" 的 loc:loc = xmlobj.xpath('//s:url[priority=1]/loc/text()', namespaces=nsmap) ,但是得到空字符串,你知道为什么吗?
  • //s:url[s:priority=1]/s:loc/text(),假设除了命名空间之外的一切都是正确的。
猜你喜欢
  • 1970-01-01
  • 2017-03-29
  • 2012-07-29
  • 2017-12-03
  • 2011-06-03
  • 1970-01-01
  • 2021-10-22
  • 2020-11-07
  • 1970-01-01
相关资源
最近更新 更多