[英]lxml etree.iterparse error “TypeError: reading file objects must return plain strings”
I would like to parse an HTML document using lxml. 我想使用lxml解析HTML文档。 I am using python 3.2.3 and lxml 2.3.4 ( http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml )
我正在使用python 3.2.3和lxml 2.3.4( http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml )
I am using the etree.iterparse
to parse the document, but it returns the following run-time error: 我使用
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
The question is: How to solve this run-time error? 问题是:如何解决这个运行时错误?
Thank you very much. 非常感谢你。
Here is the code: 这是代码:
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))
Your StringIO buffer has unicode string. 您的StringIO缓冲区具有unicode字符串。
iterparse
works with file like objects that return bytes. iterparse
适用于返回字节的文件。 The following buffer should work with iterparse: 以下缓冲区应该与iterparse一起使用:
from io import BytesIO
some_file_like = BytesIO("<root><a>data</a></root>".encode('utf-8'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.