Lxml etree.iterparse错误&Quot;TypeError:读取文件对象必须返回纯字符串

2022-04-01 00:00:00 python elementtree lxml iterparse

问题描述

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

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

Traceback (most recent call last):
  File "D:Eclipse ProjectsPython workspaceCrawlercrawler.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/lxmllxml.etree.c:98565)
  File "iterparse.pxi", line 512, in lxml.etree.iterparse._read_more_events (src/lxmllxml.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))

解决方案

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

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

相关文章