---
title: "lxml  使用试水记"
author: "caicono"
date: "2010-01-07T11:34:00Z"
tags: []
slug: "lxml"
draft: false
lastmod: "2010-01-07T11:34:00Z"
id: 609059
url: "https://caicono.iteye.com/blog/609059"
---

本人python菜鸟一个，近期对python比较感兴趣，写下安装lxml包，并且在程序开发过程中的一些心得体会和原始记录，方便以后自己查看。

里面包括lxml安装相关问题，unicode编码问题。

纯为了自己记录而已，格式和顺序都比较乱。

 

- Setuptools 和 easyInstall的关系？

setuptools是对python的package Index(CPAN PyPI distutils eggs package management)进行管理的工具，一般python安装后会自动安装setuptools，而且里面包含easyInstall脚本工具以及exe文件（windows平台上）

 

- python工具包的后缀名是.egg,.egg 是windows平台上的二进制文件，可以直接被程序easyInstall调用。

 

 

目前的setuptools只能支持到python 2.6版本，而python3.1的setuptools没有官方版本。有网友开发出了可兼容python3的setuptools. [http://regebro.wordpress.com/2009/02/01/setuptools-and-easy\_install-for-python-3/](http://regebro.wordpress.com/2009/02/01/setuptools-and-easy_install-for-python-3/)

同时指出，当前支持3.1的python库还不多。不过距离当时发表时间已经过去1年了，不知目前的python 3.1的package库支持能力如何。

 

因为我只是需要lxml包的基本功能，就不在安装包版本上花费过多精力，转向2.6版本的python继续开发？？

 

1. 去[http://codespeak.net/lxml/](http://codespeak.net/lxml/) ，下载lxml包。最新版本2.2.4，09年11月11日发布。
2. 然后根据instruction进行安装：[http://codespeak.net/lxml/installation.html](http://codespeak.net/lxml/installation.html)
3. 在此之前有两个依赖包。先不管。
4. 获取工具(也是基于python的一个功能模块)easy\_install（Easy Install is a **python module** (easy\_install) bundled with setuptools that lets you automatically download, build, install, and manage Python packages.）windows平台上，Pyhon 2.6版本会之间附带上easy\_install.exe，但在3.1版本安装目录下，没有这个安装文件。而且，pyhon3.1没有easy\_install工具。那么3.1如何安装更新包呢？ 不解。

 

 

Dov Reshef wrote:

&gt; I'm trying to install lxml 2.2.2 for python 3.1. (I'm using the egg for

&gt; python version 3, simply unpacking it to the site-packages folder). However,

&gt; when I try to use it in my code I get "ImportError: DLL load failed", which

&gt; if I understand it correctly, means that it can't find the etree.dll even

&gt; though it's right there in my site-packages folder (etree.pyd).

 

3.1 isn't 3.0 compatible, I guess.

We don't currently have binary eggs for 3.1, sorry.

 

1. 只能换到2.6平台，重新将上面的工作继续一遍.

 

C:\\Documents and Settings\\Administrator&gt;easy\_install

Easy\_install 总是不能在其它目录下运行，明明将D:\\Python26\\Scripts;加入了path路径。后来发现D:\\Python26\\Scripts;必须在D:\\Python26这个路径之后，系统才能将其识别。

 

下载lxml-2.2.4-py2.4-win32.egg，然后运行安装程序：

C:\\Documents and Settings\\Administrator&gt;easy\_install C:\\lxml-2.2.4-py2.4-win32.egg

终于将lxml装入python2.6的库中。

在文件夹：D:\\Python26\\Lib\\site-packages 可以看到新增了lxml-2.2.4-py2.4-win32.egg文件夹以及一些新的文件。

 

在python 2.6运行cmd中，终于可以import lxml了

Python3中显然依然不能导入lxml，因为目前无法安装。

 

 

终于用一种比较dirty的方式实现了对pdf文档加书签，但是还没有解决将中文写入xml文档。

 

因为在写入中文时出现错误：

        name = etree.SubElement(bookmark,'Name')

        name.text = ""+item\[0]

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes

 

读取中文txt文件需要指定编码方式，否则open函数不知如何对字节进行解码为相应的字符。

发现windows平台上python默认的编码格式为：cp936

print(locale.getpreferredencoding())

 

而且在IDLE编辑器中有一个默认设置：# -\*- coding: cp936 -\*-

这个好像就是将平台的编码格式设定为cp936的语句。不是，我将其改成utf-8, getpreferredencoding输出的依然是cp936.因为这是制定为py文件中非ascii字符的编码方式。

 

因为python2.6不支持open(‘’,encoding=’utf-8’)的语法，只好采用codecs包的open方法，但是用utf-8编码方式入读中文文件依然出现error。

import codecs

    book\_file = codecs.open('bookmark-logic.txt','r')

  File "D:\\Python26\\lib\\encodings\\utf\_8.py", line 16, in decode

    return codecs.utf\_8\_decode(input, errors, True)

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 0-1: invalid data

此时很明显是因为输入文件就不是用utf-8方式编码的。解决方法，用记事本将输入文件改成utf-8编码保存后即可。

 

但是又出现新问题，生成的文档无法正常显示中文。这是为何？？问题肯定出在这一句：

name.text = item\[0]

item的编码方式是utf-8，直接赋值给text，text可能会是unicode或者原始字符类型str,不一样。为何显示出来的unicode会是这种&#65279;编码形式呢？

 

text type is: &lt;type 'unicode'&gt;

item type is: &lt;type 'unicode'&gt;

text type is: &lt;type 'unicode'&gt;

item type is: &lt;type 'unicode'&gt;

text type is: &lt;type 'str'&gt;

item type is: &lt;type 'unicode'&gt;

 

 

&lt;?xml version="1.0" encoding="utf-8" ?&gt;

&lt;Bookmarks&gt;

  &lt;Bookmark&gt;

    &lt;Name&gt;&#65279;&#20013;&#25991;&lt;/Name&gt;

    &lt;page&gt;46&lt;/page&gt;

    &lt;level&gt;1&#13;

&lt;/level&gt;

 

对item中的中文进行utf-8编码有问题。因为item\[0]本身是unicode对象。

name.text = (""+item\[0]).encode('utf-8')

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes

name.text = (""+item\[0]).decode('utf-8')

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

 

 

题外话，在这一次python3转2.6的过程中，发现语法差异还是不小：

比如2中不支持：  #print('list display：{} {};'.format(count,item))

在3之前的版本，print都不是一个函数。