使用 Python 2.7 使用 lxml iterparse 函数的字符串绕过文件作为参数 [英] Bypass file as parameter with a string for lxml iterparse function using Python 2.7
本文介绍了使用 Python 2.7 使用 lxml iterparse 函数的字符串绕过文件作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 lxml.tree 函数 iterparse() 对 xml 树进行交互.
I am interating over an xml tree using the lxml.tree function iterparse().
这适用于输入文件
xml_source = "formatted_html_diff.xml"
context = ET.iterparse(xml_source, events=("start",))
event, root = context.next()
但是,我想在文件中使用包含相同信息的字符串.
However, I would like to use a string containing the same information in the file.
我尝试使用
context = ET.iterparse(StringIO(result), events=("start",))
但这会导致以下错误:
Traceback (most recent call last):
File "c:/Users/pag/Documents/12_raw_handle/remove_from_xhtmlv02.py", line 96, in <module>
event, root = context.next()
File "src\lxml\iterparse.pxi", line 209, in lxml.etree.iterparse.__next__
TypeError: reading file objects must return bytes objects
有谁知道我该如何解决这个错误?
Does anyone know how could I solve this error?
提前致谢.
推荐答案
使用 BytesIO
而不是 StringIO
.以下代码适用于 Python 2.7 和 Python 3:
Use BytesIO
instead of StringIO
. The following code works with both Python 2.7 and Python 3:
from lxml import etree
from io import BytesIO
xml = """
<root>
<a/>
<b/>
</root>"""
context = etree.iterparse(BytesIO(xml.encode("UTF-8")), events=("start",))
print(next(context))
print(next(context))
print(next(context))
输出:
('start', <Element root at 0x315dc10>)
('start', <Element a at 0x315dbc0>)
('start', <Element b at 0x315db98>)
这篇关于使用 Python 2.7 使用 lxml iterparse 函数的字符串绕过文件作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文