在使用Python的本地计算机上使用LXML ETREE解析XML文件时遇到问题
我在MacOSX上使用Python2.7.3,并安装了lxml版本3.3.3。我有几个xml文件在同一个目录中,例如,在使用Python的本地计算机上使用LXML ETREE解析XML文件时遇到问题,python,xml,lxml,Python,Xml,Lxml,我在MacOSX上使用Python2.7.3,并安装了lxml版本3.3.3。我有几个xml文件在同一个目录中,例如,MyDir/file1.xml和MyDir/file2.xml。我试图将每一个都引入python并提取相关信息。然而,我似乎无法让etree解析器工作。我的代码非常简单: from lxml import etree from os import listdir from os.path import isfile, join xmlfiles = [x for x i
MyDir/file1.xml
和MyDir/file2.xml
。我试图将每一个都引入python并提取相关信息。然而,我似乎无法让etree
解析器工作。我的代码非常简单:
from lxml import etree
from os import listdir
from os.path import isfile, join
xmlfiles = [x for x in listdir("MyDir") if isfile(join("MyDir",x))]
for file in xmlfiles:
doc = etree.parse(file)
get the stuff I need
但是,解析器不断向我抛出以下错误
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 3239, in lxml.etree.parse (src/lxml/lxml.etree.c:69955)
File "parser.pxi", line 1748, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:102066)
File "parser.pxi", line 1774, in lxml.etree._parseDocumentFromURL
(src/lxml/lxml.etree.c:102330)
File "parser.pxi", line 1678, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:101365)
File "parser.pxi", line 1110, in lxml.etree._BaseParser._parseDocFromFile
(src/lxml/lxml.etree.c:96817)
File "parser.pxi", line 582, in lxml.etree._ParserContext._handleParseResultDoc
(src/lxml/lxml.etree.c:91275)
File "parser.pxi", line 683, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:92461)
File "parser.pxi", line 620, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:91722)
IOError: Error reading file 'File1.xml': failed to load external entity
"File1.xml"
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
lxml.etree.parse(src/lxml/lxml.etree.c:69955)中的文件“lxml.etree.pyx”,第3239行
文件“parser.pxi”,第1748行,在lxml.etree.\u parseDocument(src/lxml/lxml.etree.c:102066)中
lxml.etree中的文件“parser.pxi”,第1774行。\u parseDocumentFromURL
(src/lxml/lxml.etree.c:102330)
文件“parser.pxi”,第1678行,在lxml.etree.\u parseDocFromFile(src/lxml/lxml.etree.c:101365)中
lxml.etree.\u BaseParser.\u parseDocFromFile中的文件“parser.pxi”,第1110行
(src/lxml/lxml.etree.c:96817)
文件“parser.pxi”,第582行,在lxml.etree.\u ParserContext.\u handleParseResultDoc
(src/lxml/lxml.etree.c:91275)
文件“parser.pxi”,第683行,在lxml.etree.\u handleParseResult(src/lxml/lxml.etree.c:92461)中
lxml.etree中的文件“parser.pxi”,第620行。\u raiseParserError(src/lxml/lxml.etree.c:91722)
IOError:读取文件“File1.xml”时出错:无法加载外部实体
“File1.xml”
我在这里看到了几个答案,但它们都是针对特定的问题,主要是向解析器提供一个html文件,而我只是向它提供一个已经存储在本地机器上的xml文件。有人能帮我弄清楚为什么这不能正常工作吗
另外,有没有比我现在采用的方法更好的方法来使用python解析和提取xml文件中的信息呢(假设我能让它工作!)
谢谢我最好使用*.xml
文件掩码。这更明确、更安全:
for filename in glob.iglob("MyDir/*.xml"):
tree = etree.parse(filename)
print tree.getroot()
希望有帮助。您没有提供完整的文件路径,因此无法加载文件 您有几个选择:
MyDir
(易碎)for
循环之前更改为MyDir
(例如import os;'os.chdir('MyDir')
)xmlfiles = [join("MyDir",x) for x in listdir("MyDir") if isfile(join("MyDir",x))]
for file in xmlfiles:
doc = etree.parse(join("MyDir",file))
#continue on