lxml etree.iterparse错误“TypeError:读取文件对象必须返回纯字符串”

时间:2012-04-20 07:48:01

标签: python lxml elementtree iterparse

我想使用lxml解析HTML文档。我使用的是python 3.2.3和lxml 2.3.4(http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

我使用etree.iterparse来解析文档,但它返回以下运行时错误:

Traceback (most recent call last):
  File "D:\Eclipse Projects\Python workspace\Crawler\crawler.py", line 12, in <module>
    for event, elements in etree.iterparse(some_file_like):
  File "iterparse.pxi", line 491, in lxml.etree.iterparse.__next__ (src/lxml\lxml.etree.c:98565)
  File "iterparse.pxi", line 512, in lxml.etree.iterparse._read_more_events (src/lxml\lxml.etree.c:98768)
TypeError: reading file objects must return plain strings

问题是:如何解决此运行时错误?

非常感谢。

以下是代码:

from io import StringIO
from lxml import etree

some_file_like = StringIO("<root><a>data</a></root>")

for event, elements in etree.iterparse(some_file_like): #<-- Run-time error happens here
    print("%s, %4s, %s" % (event, elements.tag, elements.text))

1 个答案:

答案 0 :(得分:20)

您的StringIO缓冲区有unicode字符串。 iterparse适用于返回字节的文件类对象。以下缓冲区应该与iterparse一起使用:

from io import BytesIO
some_file_like = BytesIO("<root><a>data</a></root>".encode('utf-8'))