xml.etree.ElementTree可以通过支持的有限的XPath表达式来定位元素。 语法 ElementTree支持的语法如下: 语法 说明 tag 查找所有具有指定名称tag的子元素。例如:country表示所有名为country的元素
xml.etree.ElementTree可以通过支持的有限的XPath表达式来定位元素。
语法
ElementTree支持的语法如下:
方括号表达式前面必须有标签名、星号或者其他方括号表达式。position前必须有一个标签名。
简单示例
#!/usr/bin/python # -*- coding:utf-8 -*- import os import xml.etree.cElementTree as ET xml_string="""<?xml version="1.0"?> <data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2008</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2011</year> <gdppc>59900</gdppc> <neighbor name="Malaysia" direction="N"/> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2011</year> <gdppc>2011</gdppc> <neighbor name="Costa Rica" direction="W"/> <neighbor name="Colombia" direction="E"/> </country> <country name="Washington"> <rank updated="yes">55</rank> <gdppc>13600</gdppc> </country> </data> """ root=ET.fromstring(xml_string) #查找data下所有名为country的元素 for country in root.findall("country"): print("name:"+country.get("name")) #查找country下所有名为year的元素 year=country.find("./year") if year: print("year:"+year.text) #查找名为neighbor的孙子元素 for neighbor in root.findall("*/neighbor"): print("neighbor:"+neighbor.get("name")) #查找country下的所有子元素 for ele in root.findall("country//"): print(ele.tag) #查找当前元素的父元素,结果为空 print(root.findall("..")) #查找与名为rank的孙子元素同级的名为gdppc的元素 for gdppc in root.findall("*/rank/../gdppc"): print("gdppc:"+gdppc.text) #查找data下所有具有name属性的子元素 for country in root.findall("*[@name]"): print(country.get("name")) #查找neighbor下所有具有name属性的子元素 for neighbor in root.findall("country/*[@name]"): print(neighbor.get("name")) #查找country下name属性值为Malaysia的子元素 print("direction:"+root.find("country/*[@name='Malaysia']").get("direction")) #查找root下所有包含名为year的子元素的元素 for country in root.findall("*[year]"): print("name:"+country.get("name")) #查找元素(或其子元素)文本内容为2011的元素(Python3.7+) #print(len(root.findall("*[.='2011']"))) #查找元素(或其子元素)名为gdppc,文本内容为2011的元素 for ele in root.findall("*[gdppc='2011']"): print(ele.get("name")) #查找第二个country元素 print(root.find("country[2]").get("name"))
补充知识:python lxml etree xpath定位
etree全称:ElementTree 元素树
用法:
import requests from lxml import etree response = requests.get('html') res = etree.HTML(response.text) #利用 etree.HTML 初始化网页内容 resp = res.xpath('//span[@class="green"]/text()')
以上这篇Python3 xml.etree.ElementTree支持的XPath语法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。