Windows上的lxml错误-AttributeError:模块'lxml'没有属性'etree'

use*_*748 6 python lxml anaconda

我在Windows 32位上使用带有Python 3.5的Anaconda v4.2,并希望使用lxml etree。我的Anaconda发行版包含lxml 3.6.4,但是我的IDE(PyCharm,尽管在使用Jupyter Notebook运行代码时遇到相同的错误)可以看到的唯一lxml函数是get_include()。如下代码:

import lxml
full_xml_tree = lxml.etree.parse('myfile.xml')
Run Code Online (Sandbox Code Playgroud)

只是给我错误:

AttributeError: module 'lxml' has no attribute 'etree'
Run Code Online (Sandbox Code Playgroud)

我还尝试安装Windows的VisualC ++编译器,但这并没有任何区别。我尝试在命令行上使用conda重新安装lxml,再次没有更改我的错误。我想念什么?似乎lxml.get_include()函数未找到要包含的任何文件,而且我不太了解etree.cp35-win32.pyd文件的方式(我认为其中包含已编译的etree代码?)应该与lxml软件包相关联。任何帮助,不胜感激!

凯茜

小智 7

这对于etree(ElementTree)子包的导入方式有点古怪。

您必须显式导入子包以使其可用:

import lxml.etree
full_xml_tree = lxml.etree.parse('myfile.xml')
Run Code Online (Sandbox Code Playgroud)

实现您要执行的操作的推荐方法是导入ElementTree模块:

import xml.etree.ElementTree as ET
tree = ET.parse('myfile.xml')
Run Code Online (Sandbox Code Playgroud)

参见:https : //docs.python.org/3.6/library/xml.etree.elementtree.html

为什么会这样?

想象一个具有如下目录结构的软件包:

test_pkg/__init__.py
test_pkg/shown_module.py
test_pkg/hidden_module.py
Run Code Online (Sandbox Code Playgroud)

并且其中__init__.py包含以下内容:

from . import shown_module
Run Code Online (Sandbox Code Playgroud)

使用此包,您可以shown_module直接使用:

>>> import test_pkg
>>> test_pkg.shown_module
<module 'test_pkg.shown_module' from '.../test_pkg/shown_module.py'>
Run Code Online (Sandbox Code Playgroud)

hidden_module不能直接使用:

>>> test_pkg.hidden_module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'test_pkg' has no attribute 'hidden_module'
Run Code Online (Sandbox Code Playgroud)

但是,如果导入,则可以使用:

>>> import test_pkg.hidden_module
>>> test_pkg.hidden_module
<module 'test_pkg.hidden_module' from '.../test_pkg/hidden_module.py'>
Run Code Online (Sandbox Code Playgroud)

但是,我不知道为什么ElementTree被“隐藏”。