来源:http://lxml.de/tutorial.html

lxml是python中处理xml的一个非常强大的库,可以非常方便的解析和生成xml文件。下面的内容翻译了链接中的一部分

1.生成空xml节点

from lxml import etree

root = etree.Element("root")
print(etree.tostring(root, pretty_print=True))
<root/>

2.生成xml子节点

from lxml import etree

root = etree.Element("root")
root.append(etree.Element("child1")) #方法一
child2 = etree.SubElement(root, "child2") #方法二
child2 = etree.SubElement(root, "child3")
print(etree.tostring(root))
<root>
<child1/>
<child2/>
<child3/>
</root>

3.生成带内容的xml节点

from lxml import etree

root = etree.Element("root")
root.text = "Hello World"
print(etree.tostring(root, pretty_print=True))
<root>Hello World</root>

4.属性

lxml中将属性以字典的形式存储

生成属性

from lxml import etree

root = etree.Element("root", intersting = "totally")  #方法一
root.set("hello","huhu") #方法二
root.text = "Hello World"
print(etree.tostring(root))
<root intersting="totally" hello="huhu">Hello World</root>

获取属性

方法一:

root.get("interesting")
root.get("hello")
totally
huhu

方法二:

attributes = root.attrib
print(attributes["interesting"])

遍历属性

for name, value in sorted(root.items()):
print('%s = %r' % (name, value))

5.生成特殊内容

如下xml,中间的文字被<br/>分割,需要用到.tail

<html><body>Hello<br/>World</body></html>
html = etree.Element("html")
body = etree.SubElement(html, "body")
body.text = "TEXT"
br = etree.SubElement(body, "br")
br.tail = "TAIL"
etree.tostring(html)

6.遍历

遍历节点

for element in root.iter():
print("%s - %s" % (element.tag, element.text))

遍历指定子节点,将子节点名写入iter()

for element in root.iter("child"):
print("%s - %s" % (element.tag, element.text))

7.用XPath查找节点内容

build_text_list = etree.XPath("//text()") # lxml.etree only!
print(build_text_list(html))

8.查找节点

iterfind():遍历所有节点匹配表达式

findall():返回满足匹配的节点列表

find():返回满足匹配的第一个

findtext():返回第一个满足匹配条件的.text内容

设有以下xml内容

root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>")

查找子节点

>>> print(root.find("b"))
None
>>> print(root.find("a").tag)
a

查找树中任意节点

>>> print(root.find(".//b").tag)
b
>>> [ b.tag for b in root.iterfind(".//b") ]
['b', 'b']

查找具有指定属性的节点

>>> print(root.findall(".//a[@x]")[0].tag)
a
>>> print(root.findall(".//a[@y]"))
[]

9.字符串解析为XML

>>> some_xml_data = "<root>data</root>"

>>> root = etree.fromstring(some_xml_data)
>>> print(root.tag)
root
>>> etree.tostring(root)
b'<root>data</root>'

10.使用E-factory快速生成XML和HTML

>>> from lxml.builder import E

>>> def CLASS(*args): # class is a reserved word in Python
return {"class":' '.join(args)} >>> html = page = (
E.html( # create an Element called "html"
E.head(
E.title("This is a sample document")
),
E.body(
E.h1("Hello!", CLASS("title")),
E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
E.p("This is another paragraph, with a", "\n ",
E.a("link", href="http://www.python.org"), "."),
E.p("Here are some reservered characters: <spam&egg>."),
etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
)
)
) >>> print(etree.tostring(page, pretty_print=True))
<html>
<head>
<title>This is a sample document</title>
</head>
<body>
<h1 class="title">Hello!</h1>
<p>This is a paragraph with <b>bold</b> text in it!</p>
<p>This is another paragraph, with a
<a href="http://www.python.org">link</a>.</p>
<p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p>
<p>And finally an embedded XHTML fragment.</p>
</body>
</html>

【python】lxml的更多相关文章

  1. 【python】lxml中多个xml采用相同节点时出现的问题

    今天突然发现了一个lxml的坑. 假设我们有一个节点 <id>123</id> 有两个父节点都要用上述节点,则必须把上面的节点写两遍!用同一个会出错! 出错例子: #!/usr ...

  2. 【python】lxml查找属性为指定值的节点

    假设有如下xml在/home/abc.xml位置 <A> <B id=" name="apple"/> <B id=" name= ...

  3. 【python】lxml处理命名空间

    有如下xml <A xmlns="http://This/is/a/namespace"> <B>dataB1</B> <B>dat ...

  4. 【python】自动更新pu口袋校园活动

    [python]自动更新pu口袋校园活动 脚本目标: 1. 自动爬取pu口袋校园活动,筛选出需要的活动,此处我的筛选条件是线上活动,因为可以不用去就可以白嫖学时 2. 自动发送邮件到QQ邮箱,每次只发 ...

  5. 【Python②】python之首秀

       第一个python程序 再次说明:后面所有代码均为Python 3.3.2版本(运行环境:Windows7)编写. 安装配置好python后,我们先来写第一个python程序.打开IDLE (P ...

  6. 【python】多进程锁multiprocess.Lock

    [python]多进程锁multiprocess.Lock 2013-09-13 13:48 11613人阅读 评论(2) 收藏 举报  分类: Python(38)  同步的方法基本与多线程相同. ...

  7. 【python】SQLAlchemy

    来源:廖雪峰 对比:[python]在python中调用mysql 注意连接数据库方式和数据操作方式! 今天发现了个处理数据库的好东西:SQLAlchemy 一般python处理mysql之类的数据库 ...

  8. 【python】getopt使用

    来源:http://blog.chinaunix.net/uid-21566578-id-438233.html 注意对比:[python]argparse模块 作者:limodou版权所有limod ...

  9. 【Python】如何安装easy_install?

    [Python]如何安装easy_install? http://jingyan.baidu.com/article/b907e627e78fe146e7891c25.html easy_instal ...

随机推荐

  1. Cocos2D-X 学习笔记

    1. 3.4final控制台创建项目后,安卓编译会失败,必须手动把cocos/平台/andorid/java/src目录里的文件复制到安卓项目的src文件夹即可 2. 安卓的文件目录与win的略有不同 ...

  2. android版微信5.2.1更新 支持微信聊天记录备份到电脑上

    昨天微信 5.2.1 for Android 全新发布了,和微信 5.2.1 for iPhone一样,支持拍照分享,可以把照片发送给多个朋友,最重要的一个更新是支持微信聊天记录备份到电脑(可以通过腾 ...

  3. jQuery的$.ajax示例

    $.ajax({ url: 'index.php?module=products&submod=product_experience_manage&method=ajaxGetSele ...

  4. 第26天 swift reflect

    1.reflect http://www.jianshu.com/p/b5c87824e33c 2.android studio 2.0项目1.5编译 Cause: com/android/build ...

  5. 01Getting Started---Getting Started with ASP.NET Web API 2入门WebApi2

    HTTP 不只是为了生成 web 页面.它也是建立公开服务和数据的 Api 的强大平台.HTTP 是简单的. 灵活的和无处不在.你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以达到范围 ...

  6. NoSuchMethodException问题总结

    1.编译异常,这个很容易发现并解决: method真的没有 替换jar包没有clean project. 2.编译正常,运行报错 这是一个遇到之后让人纳闷的异常,脑袋不转弯的时候真的容易被卡住.这时只 ...

  7. Android学习笔记(一)——新建一个项目

    //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! 1.打开Android Studio时出现以下界面,点击”start a new Android Studio ...

  8. 从输入 URL 到浏览器接收的过程中发生了什么事情?

    从输入 URL 到浏览器接收的过程中发生了什么事情? What really happens when you navigate to a URL 上面两篇文章都解读的很好,值得阅读. 接下来在总结一 ...

  9. BZOJ 4579: [Usaco2016 Open]Closing the Farm

    Description 依次删去一个点和它的边,问当前图是否连通. Sol 并查集. 倒着做就可以了. 每次将一个点及其的边加入,如果当前集合个数大于 1,那么就不连通. Code /******** ...

  10. VQuery选择器

    VQUery elements属性,储存选中的元素 参数 typeof的作用 字符串 class  ID tagName 函数 事件绑定 对象 直接插入 $函数 绑定事件 click方法 显示隐藏,- ...