在Python中安装lxml模块

108 投票
7 回答
249912 浏览
提问于 2025-04-16 09:24

在运行一个Python脚本的时候,我遇到了这个错误

  from lxml import etree
ImportError: No module named lxml

现在我尝试安装lxml这个库

sudo easy_install lmxl

但是它给了我下面这个错误

Building lxml version 2.3.beta1.
NOTE: Trying to build without Cython, pre-generated 'src/lxml/lxml.etree.c' needs to be available.
ERROR: /bin/sh: xslt-config: not found

** make sure the development packages of libxml2 and libxslt are installed **

正在使用libxslt的构建配置

src/lxml/lxml.etree.c:4: fatal error: Python.h: No such file or directory
compilation terminated.
error: Setup script exited with error: command 'gcc' failed with exit status 1

7 个回答

50

你需要安装Python的头文件(在debian/ubuntu系统中叫做python-dev包),才能编译lxml。此外,还需要安装libxml2、libxslt、libxml2-dev和libxslt-dev这些库:

apt-get install python-dev libxml2 libxml2-dev libxslt-dev
97

我通过升级lxml的版本解决了这个问题,具体操作是:

pip install --upgrade lxml
112

只需这样做:

sudo apt-get install python-lxml

对于Python 2(比如,Inkscape需要的版本):

sudo apt-get install python2-lxml

如果你打算从源代码安装,那么albertov的回答会对你有帮助。不过,除非有特别的原因,不然就直接从软件库安装就好了。

撰写回答