当前位置:首页 » 编程语言 » pythonlibxml2

pythonlibxml2

发布时间: 2023-05-24 10:04:16

编译安装python需要哪些依赖

依赖库:

//使用apt 安装即可
1.gcc, make, zlib1g-dev(压缩解压缩库)
安装过程需要的库。
2.libbz2-dev
bz2支持库,若在编译安装python前没有安装,将无法通过pip install 安装提供bz2格式的第三方库,会出现unsupported archive format: .tar.bz2的错误,例如爬虫库Scrapy依赖的Twisted。
3.libsqlite3-dev
sqlite3支持库,若在编译安装python前没有安装,则python中会缺失sqlite3模块,当引入sqlite3或使用依赖sqllite3的第三方库(例如Scrapy)时,会出现ImportError: No mol named _sqllite3的错误。
//以上为编译安装前需要安装的库,可能不够全面,会不断补充。
4.其他:安装第三方库需要的库
python3-dev, libxml2-dev, libxslt1, libffi-dev, libssl-dev等,在安装第三方库会有具体说明,不做过多解释。

安装:

//通过wget获取压缩包,这里选择3.6.1版
wget https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tar.xz
//解压
tar xJf Python-3.6.1.tar.xz
cd Python-3.6.1
./configure
make
/*这步如果需要sudo,请使用sudo -H命令,即sudo -H make install,避免pip等模块安装失败。
错误示例(pip安装失败):The directory '/home/ls/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
*/
make install

② python lxml etree怎么甩

lxml是Python语言中处理XML和HTML功能最丰富,最易于使用的库。

lxml是libxml2和libxslt两个C库的Python化绑定,它的独特之处在于兼顾了这些库的速度和功能完整性,同时还具有Python API的简介。兼容ElementTree API,但是比它更优越。

用libxml2编程就像是一个异于常人的陌生人的令人惊恐的拥抱,它看上去可以满足你一切疯狂的梦想,但是你的内心深处一直在警告你,你有可能会以最糟糕的方式遭殃,所以就有了lxml。



这是一个用lxml.etree来处理XML的教程,它简单的概述了ElementTree API的主要概念,同时有一些能让你的程序生涯更轻松的简单的提高。


首先是导入lxml.etree的方式:

fromlxmlimportetree

为了协助代码的可移植性,本教程中的例子很明显可以看出,一部分API是lxml.etree在ElementTree API(由Fredrik Lundh 的ElementTree库定义)的基础上的扩展。

Element是ElementTree API的主要容器类,大部分XML tree的功能都是通过这个类来实现的,Element的创建很容易:

root=etree.Element("root")

element的XML tag名通过tag属性来访问

>>>printroot.tag
root



许多Element被组织成一个XML树状结构,创建一个子element并添加进父element使用append方法:

>>>root.append(etree.Element("和耐child1"))



还有一个更简短更有效的方法:the SubElement,它的参数和element一样,但是需要父element作为第一个参数:

>>>child2=etree.SubElement(root,"child2")
>>>child3=etree.SubElement(root,"child3")



可以序列化你创建的树:

>>>print(etree.tostring(root,pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>



为了更方便直胡棚野观的访问这些子节点,element模仿了正常的Python链:

>>>child=root[0]>>>print(child.tag)
child1
>>>print(len(root))
>>>root.index(root[1])#lxml.etreeonly!
>>>children=list(root)>>>forchildinroot:...print(child.tag)child1child2
child3
>>>root.insert(0,etree.Element("child0"))>>>start裤喊=root[:1]>>>end=root[-1:]>>>print(start[0].tag)child0>>>print(end[0].tag)child3


还可以根据element的真值看其是否有孩子节点:

ifroot:#thisnolongerworks!
print("Therootelementhaschildren")


用len(element)更直观,且不容易出错:

>>>print(etree.iselement(root))#testifit'ssomekindofElement
True
>>>iflen(root):#testifithaschildren
...print("Therootelementhaschildren")
Therootelementhaschildren



还有一个重要的特性,原文的句子只可意会,看例子应该是能看懂什么意思吧。

>>>forchildinroot:...print(child.tag)child0child1child2child3>>>root[0]=root[-1]#移动了element>>>forchildinroot:...print(child.tag)child3child1child2>>>l=[0,1,2,3]>>>l[0]=l[-1]>>>l[3,1,2,3]
>>>rootisroot[0].getparent()#lxml.etreeonly!.etree,'sstandardlibrary:>>>fromimportdeep>>>element=etree.Element("neu")>>>element.append(deep(root[1]))>>>print(element[0].tag)child1>>>print([c.tagforcinroot])['child3','child1','child2']



XML支持属性,创建方式如下:

>>>root=etree.Element("root",interesting="totally")
>>>etree.tostring(root)
b'<rootinteresting="totally"/>'



属性是无序的键值对,所以可以用element类似于字典接口的方式处理:

>>>print(root.get("interesting"))
totally
>>>print(root.get("hello"))
None
>>>root.set("hello","Huhu")
>>>print(root.get("hello"))
Huhu
>>>etree.tostring(root)
b'<rootinteresting="totally"hello="Huhu"/>'
>>>sorted(root.keys())
['hello','interesting']
>>>forname,valueinsorted(root.items()):
...print('%s=%r'%(name,value))
hello='Huhu'
interesting='totally'

如果需要获得一个类似dict的对象,可以使用attrib属性:

>>>attributes=root.attrib
>>>print(attributes["interesting"])
totally
>>>print(attributes.get("no-such-attribute"))
None
>>>attributes["hello"]="GutenTag"
>>>print(attributes["hello"])
GutenTag
>>>print(root.get("hello"))
GutenTag

既然attrib是element本身支持的类似dict的对象,这就意味着任何对element的改变都会影响attrib,反之亦然。这还意味着只要element的任何一个attrib还在使用,XML树就一直在内存中。通过如下方法,可以获得一个独立于XML树的attrib的快照:

>>>d=dict(root.attrib)
>>>sorted(d.items())
[('hello','GutenTag'),('interesting','totally')]

linux下面装libxml2-python老是装不上,怎么回事

把linux下面的python从2.4更新到2.7了,然后用sudo yum install libxml2-python命令安装libxml2每次都提示成功,但是进入到python环境输入import libxml2都提示错误,后来发现用yum install 安装默认安装到了python2.4下面的site-packages下

④ python使用xpath(超详细)

使用时先安装 lxml 包

开始使用 #

和beautifulsoup类似,首先我们需要得到一个文档树

把文本转换成一个文档树对象

from lxml import etreeif __name__ == '__main__':doc='''

把文件转换成一个文档树对象

fromlxmlimportetree# 读取外部文件 index.htmlhtml = etree.parse('./index.html')result = etree.tostring(html, pretty_print=True)#pretty_print=True 会格式化输出print(result)

均会打印出文档内容

节点、元素、属性、内容 #

xpath 的思想是通过 路径表达 去寻找节点。节点包括元素,属性,和内容

元素举例

html --->...div --->

这里我们可以看到,这里的元素和html中的标签一个意思。单独的元素是无法表达一个路径的,所以单独的元素不能独立使用

路径表达式 #

/  根节点,节点分隔符,//  任意位置.  当前节点..  父级节点@  属性

通配符 #

*  任意元素@*  任意属性node()  任意子节点(元素,属性,内容)

谓语 #

使用中括号来限定元素,称为谓语

//a[n] n为大于零的整数,代表子元素排在第n个位置的 元素//a[last()]  last()  代表子元素排在最后个位置的 元素//a[last()-]  和上面同理,代表倒数第二个//a[position()<3] 位置序号小于3,也就是前两个,这里我们可以看出xpath中的序列是从1开始//a[@href]    拥有href的 元素//a[@href='www..com']    href属性值为'www..com'的 元素//book[@price>2]  price值大于2的元素

多个路径 #

用| 连接两个表达式,可以进行 或匹配

//book/title | //book/price

函数 #

xpath内置很多函数。更多函数查看 https://www.w3school.com.cn/xpath/xpath_functions.asp

contains(string1,string2)

starts-with(string1,string2)

ends-with(string1,string2) #不支持

upper-case(string) #不支持

text()

last()

position()

node()

可以看到last()也是个函数,在前面我们在谓语中已经提到过了

案例 #

定位元素 #

匹配多个元素,返回列表

fromlxmlimportetreeif__name__ =='__main__':doc='''

【结果为】

[<Element li at 0x2b41b749848>, <Element li at 0x2b41b749808>, <Element li at 0x2b41b749908>, <Element li at 0x2b41b749948>, <Element li at 0x2b41b749988>][]  #没找到p元素

html = etree.HTML(doc)print(etree.tostring(html.xpath("//li[@class='item-inactive']")[0]))print(html.xpath("//li[@class='item-inactive']")[0].text)print(html.xpath("//li[@class='item-inactive']/a")[0].text)print(html.xpath("//li[@class='item-inactive']/a/text()"))print(html.xpath("//li[@class='item-inactive']/.."))print(html.xpath("//li[@class='item-inactive']/../li[@class='item-0']"))

【结果为】

b' third item \n                'None    #因为第三个li下面没有直接text,Nonethird item  #['third item'][<Element ul at 0x19cd8c4c848>][<Element li at 0x15ea3c5b848>, <Element li at 0x15ea3c5b6c8>]

使用函数 #

contains #

有的时候,class作为选择条件的时候不合适@class='....' 这个是完全匹配,当王爷样式发生变化时,class或许会增加或减少像active的class。用contains就能很方便

from lxml import etreeif __name__ == '__main__':doc='''

【结果为】

[<Element p at 0x23f4a9d12c8>, <Element li at 0x23f4a9d13c8>, <Element li at 0x23f4a9d1408>, <Element li at 0x23f4a9d1448>, <Element li at 0x23f4a9d1488>]

starts-with #

from lxml import etreeif __name__ == '__main__':doc='''

【结果为】

[<Element ul at 0x23384e51148>, <Element p at 0x23384e51248>, <Element li at 0x23384e51288>, <Element li at 0x23384e512c8>, <Element li at 0x23384e51308>, <Element li at 0x23384e51388>][<Element ul at 0x23384e51148>]

ends-with #

print(html.xpath("//*[ends-with(@class,'ul')]"))

【结果为】

Traceback (most recent call last):File"F:/OneDrive/pprojects/shoes-show-spider/test/xp5_test.py",line18,inprint(html.xpath("//*[ends-with(@class,'ul')]"))File"src\lxml\etree.pyx",line1582,inlxml.etree._Element.xpathFile"src\lxml\xpath.pxi",line305,inlxml.etree.XPathElementEvaluator.__call__File"src\lxml\xpath.pxi",line225,inlxml.etree._XPathEvaluatorBase._handle_resultlxml.etree.XPathEvalError: Unregisteredfunction

看来python的lxml并不支持有的xpath函数列表

upper-case #

和ends-with函数一样,也不支持。同样报错lxml.etree.XPathEvalError: Unregistered function

print(html.xpath("//a[contains(upper-case(@class),'ITEM-INACTIVE')]"))

text、last #

#最后一个li被限定了print(html.xpath("//li[last()]/a/text()"))#会得到所有的`<a>`元素的内容,因为每个<a>标签都是各自父元素的最后一个元素。#本来每个li就只有一个<a>子元素,所以都是最后一个print(html.xpath("//li/a[last()]/text()"))print(html.xpath("//li/a[contains(text(),'third')]"))

【结果为】

['fifth item']['second item', 'third item', 'fourth item', 'fifth item'][<Element a at 0x26ab7bd1308>]

position #

print(html.xpath("//li[position()=2]/a/text()"))#结果为['third item']

上面这个例子我们之前以及讲解过了

* 这里有个疑问,就是position()函数能不能像text()那样用呢

print(html.xpath("//li[last()]/a/position()"))#结果  lxml.etree.XPathEvalError: Unregisteredfunction

这里我们得到一个结论,函数不是随意放在哪里都能得到自己想要的结果

node #

返回所有子节点,不管这个子节点是什么类型(熟悉,元素,内容)

print(html.xpath("//ul/li[@class='item-inactive']/node()"))print(html.xpath("//ul/node()"))

【结果为】

[]['\n                ', , '\n                ', , '\n                ', , '\n                ', , '\n                ', , ' 闭合标签\n            ']

获取内容 #

**刚刚已经提到过,可以使用.text和text()的方式来获取元素的内容

from lxml import etreeif __name__ == '__main__':doc='''

【结果为】

['first item','second item','third item','fourth item','fifth item']first item18['\n                ','\n                ','\n                ','\n                ','\n                ',' 闭合标签\n            ']

看到这里,我们观察到text()和.text的区别。自己总结吧。不太好表达,就不表达了

获取属性 #

print(html.xpath("//a/@href"))print(html.xpath("//li/@class"))

【结果为】

['link1.html', 'link2.html', 'link3.html', 'link4.html', 'link5.html']['item-0active', 'item-1', 'item-inactive', 'item-1', 'item-0']

自定义函数 #

我们从使用函数的过程中得到结论,就是有的函数不支持,有的支持,那问题来了,到底那些方法支持呢。我们在lxml官网找到了答案。 https://lxml.de/xpathxslt.html 。lxml 支持XPath 1.0 ,想使用其他扩展,使用libxml2,和libxslt的标准兼容的方式。 XPath 1.0官方文档  以及其他版本的XPath文档  https://www.w3.org/TR/xpath/

lxml supports XPath1.0, XSLT1.0andthe EXSLT extensions through libxml2andlibxsltina standards compliant way.

除此之外,lxml还提供了自定义函数的方式来扩展xpath的支持度  https://lxml.de/extensions.html

from lxml import etree#定义函数def ends_with(context,s1,s2):return s1[0].endswith(s2)if __name__ == '__main__':doc='''

【结果为】

[<Element li at 0x2816ed30548>, <Element li at 0x2816ed30508>]['first item', 'third item']

形参s1会传入xpath中的第一个参数@class,但这里注意@class是个列表

形参s2会传入xpath中的第二个参数'active','active'是个字符串

官网例子 https://lxml.de/extensions.html

defhello(context, a):return"Hello %s"% afromlxmlimportetreens = etree.FunctionNamespace(None)ns['hello'] = helloroot = etree.XML('<a><b>Haegar</b></a>')print(root.xpath("hello('Dr. Falken')"))# 结果为 Hello Dr. Falken

⑤ libxml2-2.9.1make 出现错误,求大神解决,错误如下

You need the development library libpython-dev:
sudo apt-get install libpython-dev

⑥ centos7怎么安装 安装libxml2,libxslt,lxml python

lxml 依赖 libxml2 和 libxslt 的开发版本
看看唤含系统上缺少哪一个版本就装哪一和键笑个libxslt-devel
再次安亮扮装 lxml

⑦ python如何使用libxml2

直接import libxml2就可以导入坦友隐libxml2库了, 然后直接调用里面的方法就行了让厅.我也看过libxml2的文档,给的定义全是基于C语言的, 但是python已经有它的绑告蚂定库了, 也就是说, 所以里面的函数, 在python都可以调用.至于类的使用, 我还没有研究到. 直接写关于python调用libxml2的文章太少了...得自己摸索了. 查看原帖>>

⑧ python导入libxml2dom不成功,求助

最近一个python项目需要用到libxml2dom这个包,然后就pip安装之,之后验证安装是否成功:

shandow@mac:~ > python

Python 2.7.5 (default, Mar 9 2014, 22:15:05)

[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin

Type "help", "right", "credits" or "license" for more information.

>>>拦谨笑 import libxml2dom

Traceback (most recent call last):

File "<stdin>", line 1, in <mole>

File "/Library/Python/2.7/site-packages/libxml2dom/__init__.py", line 24, in <mole>

from libxml2dom.macrolib import *

File "/Library/Python/2.7/site-packages/libxml2dom/macrolib/__init__.py", line 26, in <mole>

from libxml2dom.macrolib.macrolib import *

File "/Library/Python/2.7/site-packages/libxml2dom/macrolib/macrolib.py", line 30, in <mole>

from libxmlmods import libxml2mod

ImportError: No mole named libxmlmods

意思是缺乏libxmlmods库,使用晌渣pip安装之,提示找不到。。。。好吧,度娘问吧,找到一个类似libxml2dom的官方声明似的网站:

libxml2dom

Current release: libxml2dom 0.5 (requiring the low-level libxml2 Python bindings, typically provided by the python-libxml2 or libxml2-python packages for various GNU/Linux distributions: Ubuntu, Debian, Fedora, Red Hat, SuSE)
Introction
The libxml2dom package provides a traditional DOM wrapper around the Python bindings for libxml2. In contrast to the standard libxml2 bindings, libxml2dom provides an API reminiscent of minidom, pxdom and other Python-based and Python-related XML toolkits. Performance is fairly respectable since libxml2dom makes direct use of libxml2mod - the low-level wrapping of libxml2 for Python. Moreover, serialisation of documents is much faster than many other toolkits because libxml2dom can make direct use of libxml2 rather than employing Python-level mechanisms to visit and serialise nodes.
Copyright and Licence
libxml2dom is licensed under the LGPL version 3 (or later).

这里第一句话就是libxml2dom依赖libxml2库,可以通过查找python-libxml2或者libxml2-python下载,可是偶使用pip安装都提示找不到资源。简含。。。好吧,再次度娘,手动下载了这个包。这里贴出我分享出来的地址:libxml2下载(我的是mac
os系统,windows系统的自行下载吧,哈哈。。。)再说下mac os下如何安装:
1.先把下载的tar包放到自己python环境的site-packages,我的是:
/Library/Python/2.7/site-packages
2.解压:sudo tar -xvf libxml2-2.7.8.tar
3.进入解压后的文件夹,由于是源码包需要编译安装:
cd libxml2-2.7.8
sudo ./configure
sudo make
sudo make install
好了,如果没有报错就ok了,测试下把:
python
import libxml2
提示没有这个模块,说明没有导成功,郁闷。。。。
重新进入文件夹 :
cd libxml2-2.7.8
发现这个文件夹中有个python文件夹,进入:

shandow@mac:/Library/Python/2.7/site-packages/libxml2-2.7.8 > cd python/
shandow@mac:/Library/Python/2.7/site-packages/libxml2-2.7.8/python > ll
total 5704
-rw-r--r-- 1 root network 132 11 17 10:46 MANIFEST
-rw-r--r-- 1 root network 31357 11 17 10:43 Makefile
-rw-rw-r--@ 1 50138 network 1542 11 4 2010 Makefile.am
-rw-rw-r--@ 1 50138 network 32443 11 5 2010 Makefile.in
-rw-rw-r--@ 1 50138 network 1272 9 24 2009 README
-rw-rw-r--@ 1 50138 network 1623 9 24 2009 TODO
drwxr-xr-x 4 root network 136 11 17 10:46 build
-rw-rw-r--@ 1 50138 network 15061 9 24 2009 drv_libxml2.py
-rw-r--r-- 1 root network 0 11 17 10:44 gen_prog
-rwxrwxr-x@ 1 50138 network 47541 10 16 2010 generator.py
-rw-rw-r--@ 1 50138 network 104464 11 3 2010 libxml.c
-rw-r--r-- 1 root network 271 11 17 10:44 libxml.lo
-rw-r--r-- 1 root network 297240 11 17 10:44 libxml.o
-rw-rw-r--@ 1 50138 network 22817 10 12 2010 libxml.py
-rw-r--r-- 1 root network 126532 11 17 10:44 libxml2-export.c
-rw-r--r-- 1 root network 434813 11 17 10:44 libxml2-py.c
-rw-r--r-- 1 root network 112512 11 17 10:44 libxml2-py.h
-rw-r--r-- 1 root network 283 11 17 10:44 libxml2-py.lo
-rw-r--r-- 1 root network 819684 11 17 10:44 libxml2-py.o
-rw-rw-r--@ 1 50138 network 18669 10 12 2010 libxml2-python-api.xml
-rw-r--r-- 1 root network 341257 11 17 10:44 libxml2.py
-rw-r--r-- 1 root network 318440 11 17 10:44 libxml2class.py
-rw-r--r-- 1 root network 22768 11 17 10:44 libxml2class.txt
-rw-r--r-- 1 root network 1166 11 17 10:44 libxml2mod.la
-rw-rw-r--@ 1 50138 network 7277 10 12 2010 libxml_wrap.h
-rwxr-xr-x 1 root network 6685 11 17 10:43 setup.py
-rwxrwxr-x@ 1 50138 network 6707 9 24 2009 setup.py.in
drwxrwxr-x@ 55 50138 network 1870 11 17 10:43 tests
-rw-rw-r--@ 1 50138 network 21068 10 12 2010 types.c
-rw-r--r-- 1 root network 268 11 17 10:44 types.lo
-rw-r--r-- 1 root network 63320 11 17 10:44 types.o
shandow@mac:/Library/Python/2.7/site-packages/libxml2-2.7.8/python >
参照网上说的python第三方包的安装方式:
sudo python setup.py build
sudo python setup.py install
这两句运行完后,重新进入site-packages文件夹,发现多了libxml2的egg-info文件:

再次测试:

shandow@mac:/Library/Python/2.7/site-packages > python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "right", "credits" or "license" for more information.
>>> import libxml2
>>> import libxml2dom
>>>
libxml2安装成功了,libxml2dom也不会报错了,大功告成。。。。。网上网络,google都没有这个问题的解决办法,作者这里原创一个,哈哈。。。

⑨ python lxml库怎么安装

lxml是Python中与XML及HTML相关功能中最丰富和最容易使用的库。lxml并不是Python自带的包,而是为libxml2和libxslt库的一个Python化的绑定。它与众不同的地方是它兼顾了这些库的速度和功能完整性,以及纯Python API的简洁性,与大家熟知的ElementTree API兼容但比之更优越!但安装lxml却又有点麻烦,因为存在依赖,直接安装的话用easy_install, pip都不能成功,会报gcc错误。下面列出来Windows、Linux下面的安装方法:
【Windows系统】
先确保Python已经安装好,环境变量也配置好了,相应的的easy_install、pip也安装好了.
1. 执行 pip install virtualenv
[python] view plain print?
C:\>pip install virtualenv
Requirement already satisfied (use --upgrade to upgrade): virtualenv in c:\python27\lib\site-package
s\virtualenv-12.0.4-py2.7.egg
2. 从官方网站下载与系统,Python版本匹配的lxml文件:
http //pypi.python.org/pypi/lxml/2.3/
NOTE:
比如说我的电脑是Python 2.7.4, 64位操作系统,那么我就可以下载
[python] view plain print?
lxml-2.3-py2.7-win-amd64.egg (md5) # Python Egg

lxml-2.3.win-amd64-py2.7.exe (md5) # MS Windows installer
3. 执行 easy_install lxml-2.3-py2.7-win-amd64.egg
[python] view plain print?
D:\Downloads>easy_install lxml-2.3-py2.7-win-amd64.egg # 进入该文件所在目录执行该命令
Processing lxml-2.3-py2.7-win-amd64.egg
creating c:\python27\lib\site-packages\lxml-2.3-py2.7-win-amd64.egg
Extracting lxml-2.3-py2.7-win-amd64.egg to c:\python27\lib\site-packages
Adding lxml 2.3 to easy-install.pth file
Installed c:\python27\lib\site-packages\lxml-2.3-py2.7-win-amd64.egg
Processing dependencies for lxml==2.3
Finished processing dependencies for lxml==2.3
NOTE:
1. 可用exe可执行文件,方法更简单直接安装就可以
2. 可用easy_install安装方式,也可以用pip的方式
[python] view plain print?
#再执行下,就安装成功了!
>>> import lxml
>>>
3. 如用pip安装,常用命令就是:
pip install simplejson # 安装Python包
pip install --upgrade simplejson # 升级Python包
pip uninstall simplejson # 卸载Python包
4. 如用Eclipse+Pydev的开发方式,需要移除旧包,重新加载一次
Window --> Preferences --> PyDev --> Interperter-python # 否则导包的时候会报错
【Linux系统】
因为lxml依赖的包如下:
libxml2, libxml2-devel, libxlst, libxlst-devel, python-libxml2, python-libxslt
所以安装步骤如下:
第一步: 安装 libxml2
$ sudo apt-get install libxml2 libxml2-dev
第二步: 安装 libxslt
$ sudo apt-get install libxlst libxslt-dev
第三步: 安装 python-libxml2 和 python-libxslt
$ sudo apt-get install python-libxml2 python-libxslt
第四步: 安装 lxml
$ sudo easy_install lxml

⑩ 如何用python读取xml文件

一、简介

XML(eXtensible Markup Language)指可扩展标记语言,被设计用来传输和存储数据,已经日趋成为当前许多新生技术的核心,在不同的领域都有着不同的应用。它是web发展到一定阶段的必然产物,既具有SGML的核心特征,又有着HTML的简单特性,还具有明确和结构良好等许多新的特性。
python解析XML常见的有三种方法:一是xml.dom.*模块,它是W3C DOM API的实现,若需要处理DOM API则该模块很适合,注意xml.dom包里面有许多模块,须区分它们间的不同;二是xml.sax.*模块,它是SAX API的实现,这个模块牺牲了便捷性来换取速度和内存占用,SAX是一个基于事件的API,这就意味着它可以“在空中”处理庞大数量的的文档,不用完全加载进内存;三是xml.etree.ElementTree模块(简称 ET),它提供了轻量级的Python式的API,相对于DOM来说ET 快了很多,而且有很多令人愉悦的API可以使用,相对于SAX来说ET的ET.iterparse也提供了 “在空中” 的处理方式,没有必要加载整个文档到内存,ET的性能的平均值和SAX差不多,但是API的效率更高一点而且使用起来很方便。
二、详解

解析的xml文件(country.xml):
在CODE上查看代码片派生到我的代码片

<?xml version="1.0"?>
<data>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>


1、xml.etree.ElementTree

ElementTree生来就是为了处理XML,它在Python标准库中有两种实现:一种是纯Python实现的,如xml.etree.ElementTree,另一种是速度快一点的xml.etree.cElementTree。注意:尽量使用C语言实现的那种,因为它速度更快,而且消耗的内存更少。
在CODE上查看代码片派生到我的代码片

try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET


这是一个让Python不同的库使用相同API的一个比较常用的办法,而从Python 3.3开始ElementTree模块会自动寻找可用的C库来加快速度,所以只需要import xml.etree.ElementTree就可以了。
在CODE上查看代码片派生到我的代码片

#!/usr/bin/evn python
#coding:utf-8

try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import sys

try:
tree = ET.parse("country.xml") #打开xml文档
#root = ET.fromstring(country_string) #从字符串传递xml
root = tree.getroot() #获得root节点
except Exception, e:
print "Error:cannot parse file:country.xml."
sys.exit(1)
print root.tag, "---", root.attrib
for child in root:
print child.tag, "---", child.attrib

print "*"*10
print root[0][1].text #通过下标访问
print root[0].tag, root[0].text
print "*"*10

for country in root.findall('country'): #找到root节点下的所有country节点
rank = country.find('rank').text #子节点下节点rank的值
name = country.get('name') #子节点下属性name的值
print name, rank

#修改xml文件
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)

tree.write('output.xml')


运行结果:

三、总结
(1)Python中XML解析可用的类库或模块有xml、libxml2 、lxml 、xpath等,需要深入了解的还需参考相应的文档。
(2)每一种解析方式都有自己的优点和缺点,选择前可以综合各个方面的性能考虑。
(3)若有不足,请留言,在此先感谢!

热点内容
ubuntuphp版本 发布:2024-05-19 21:59:12 浏览:928
解压文案馆 发布:2024-05-19 21:58:54 浏览:870
苏宁访问数 发布:2024-05-19 21:53:49 浏览:580
湿地下载ftp 发布:2024-05-19 21:46:10 浏览:487
java二分查找算法 发布:2024-05-19 21:37:38 浏览:347
所有编程语言 发布:2024-05-19 21:33:55 浏览:665
c语言1到10的阶乘的和 发布:2024-05-19 21:32:25 浏览:628
php匹配标点符号 发布:2024-05-19 21:14:49 浏览:753
可以拍照输入的c语言编译器 发布:2024-05-19 21:09:47 浏览:182
解压升降机 发布:2024-05-19 20:51:11 浏览:968