![](/img/trans.png)
[英]Parse an xml file to extract element values using lxml and XPath in python
[英]Using lxml xpath to parse xml file
我正在使用 lxml XPath 来解析以下 xml 文件
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
<loc>
https://www.reuters.com/article/us-campbellsoup-thirdpoint/campbell-soup-nears-deal-with-third-point-to-end-board-challenge-sources-idUSKCN1NU11I
</loc>
<image:image>
<image:loc>
https://www.reuters.com/resources/r/?m=02&d=20181126&t=2&i=1328589868&w=&fh=&fw=&ll=460&pl=300&r=LYNXNPEEAO0WM
</image:loc>
</image:image>
<news:news>
<news:publication>
<news:name>Reuters</news:name>
<news:language>eng</news:language>
</news:publication>
<news:publication_date>2018-11-26T02:55:00+00:00</news:publication_date>
<news:title>
Campbell Soup nears deal with Third Point to end board challenge: sources
</news:title>
<news:keywords>Headlines,Business, Industry</news:keywords>
<news:stock_tickers>NYSE:CPB</news:stock_tickers>
</news:news>
</url>
</urlset>
Python代码示例
import lxml.etree
import lxml.html
import requests
def main():
r = requests.get("https://www.reuters.com/sitemap_news_index1.xml")
namespace = "http://www.google.com/schemas/sitemap-news/0.9"
root = lxml.etree.fromstring(r.content)
records = root.xpath('//news:title', namespaces = {"news": "http://www.google.com/schemas/sitemap-news/0.9"})
for record in records:
print(record.text)
records = root.xpath('//sitemap:loc', namespaces = {"sitemap": "http://www.sitemaps.org/schemas/sitemap/0.9"})
for record in records:
print(record.text)
if __name__ == "__main__":
main()
目前,我使用 XPath 来获取所有URL和title ,但这不是我想要的,因为我不知道哪个 URL 属于哪个标题。 我的问题是如何获取每个<url>
,然后将每个<url>
作为项目循环以获取相应的<loc>
和<news:keywords>
等。谢谢!
编辑:期待输出
foreach <url>
get <loc>
get <news:publication_date>
get <news:title>
使用相对 XPath 从每个标题获取其关联的 URL:
ns = {
"news": "http://www.google.com/schemas/sitemap-news/0.9",
"sitemap": "http://www.sitemaps.org/schemas/sitemap/0.9",
"image": "http://www.google.com/schemas/sitemap-image/1.1"
}
r = requests.get("https://www.reuters.com/sitemap_news_index1.xml")
root = lxml.etree.fromstring(r.content)
for title in root.xpath('//news:title', namespaces=ns):
print(title.text)
loc = title.xpath('ancestor::sitemap:url/sitemap:loc', namespaces=ns)
print(loc[0].text)
练习:重写此代码以从 URL 获取关联的标题。
注意:标题(可能还有 URL)似乎是 HTML 转义的。 使用unescape()
函数
from html import unescape
逃避他们。
答案是
from datetime import datetime
from html import unescape
from lxml import etree
import requests
r = requests.get("https://www.reuters.com/sitemap_news_index1.xml")
root = etree.fromstring(r.content)
ns = {
"news": "http://www.google.com/schemas/sitemap-news/0.9",
"sitemap": "http://www.sitemaps.org/schemas/sitemap/0.9",
"image": "http://www.google.com/schemas/sitemap-image/1.1"
}
for url in root.iterfind("sitemap:url", namespaces=ns):
loc = url.findtext("sitemap:loc", namespaces=ns)
print(loc)
title = unescape(url.findtext("news:news/news:title", namespaces=ns))
print(title)
date = unescape(url.findtext("news:news/news:publication_date", namespaces=ns))
date = datetime.strptime(date, '%Y-%m-%dT%H:%M:%S+00:00')
print(date)
经验法则是:
尽量不要使用 xpath 。 使用 find、findall、iterfind 代替 xpath。 xpath 是一种比 find、findall 或 iterfind 更复杂的算法,它需要更多的时间和资源。
使用iterfind而不是使用 findall。 因为 iterfind 将产生返回项目。 也就是说,它将一次返回一项。 因此它使用更少的内存。
如果您只需要文本,请使用findtext 。
更一般的规则是阅读官方文档。
首先,让我们创建 3 个 for 循环函数并比较它们。
def for1():
for url in root.iterfind("sitemap:url", namespaces=ns):
pass
def for2():
for url in root.findall("sitemap:url", namespaces=ns):
pass
def for3():
for url in root.xpath("sitemap:url", namespaces=ns):
pass
功能 | 时间 |
---|---|
root.iterfind |
70.5 微秒 ± 543 纳秒 |
root.findall |
72.3 微秒 ± 839 纳秒 |
root.xpath |
84.8 微秒 ± 567 纳秒 |
我们可以看到 iterfind 是预期的最快的。
接下来,让我们检查一下 for 循环内的语句。
陈述 | 时间 |
---|---|
url.xpath('string(news:news/news:title)', namespaces=ns) |
15.7 微秒 ± 112 纳秒 |
url_item.xpath('news:news/news:title', namespaces=ns)[0].text |
14.4 微秒 ± 53.7 纳秒 |
url_item.find('news:news/news:title', namespaces=ns).text |
3.74 微秒 ± 60 纳秒 |
url_item.findtext('news:news/news:title', namespaces=ns) |
3.71 微秒 ± 40.3 纳秒 |
从上表中,我们可以看到 find/findtext 比 xpath 快 4 倍。 findtext 甚至比 find 更快。
与 Tomalak 的 8.33 ms ± 52.4 µs 相比,此答案仅需 3.41 ms ± 53 µs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.