温馨提示×

python中怎么用xpath解析数据

小亿
87
2024-01-11 14:59:58
栏目: 编程语言

Python中可以使用lxml库中的etree模块来解析数据。下面是一个使用XPath解析数据的简单示例:

from lxml import etree

# 创建一个XML文档并解析
xml_data = """
<books>
    <book>
        <title>Python Cookbook</title>
        <author>David Beazley</author>
        <year>2013</year>
    </book>
    <book>
        <title>Fluent Python</title>
        <author>Luciano Ramalho</author>
        <year>2015</year>
    </book>
</books>
"""
root = etree.fromstring(xml_data)

# 使用XPath选择元素
titles = root.xpath("//title/text()")
authors = root.xpath("//author/text()")
years = root.xpath("//year/text()")

# 打印解析结果
for title, author, year in zip(titles, authors, years):
    print(f"Title: {title}")
    print(f"Author: {author}")
    print(f"Year: {year}")
    print("---")

输出结果如下:

Title: Python Cookbook
Author: David Beazley
Year: 2013
---
Title: Fluent Python
Author: Luciano Ramalho
Year: 2015
---

在上面的示例中,使用etree.fromstring()方法将XML字符串解析为一个Element对象。然后,可以使用xpath()方法使用XPath表达式选择相应的元素。最后,使用text属性获取元素的文本内容。

0