强制转换为Unicode:需要字符串或缓冲区,发现xml.etree._ElementTree

0 投票
1 回答
2050 浏览
提问于 2025-04-17 14:04

我刚开始学习Python,遇到了以下错误。

$ python testrun.py 
Traceback (most recent call last):
  File "testrun.py", line 13, in <module>
    with open(tree, 'w') as file_handle:
TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

使用这段代码:

from lxml import etree
tree = etree.parse('testregression_config.xml')

for elem in tree.findall('.//xmpp'):
    #assert elem.attrib['name'] == 'test02'
    elem.attrib['name'] == 'test03'

for elem in tree.findall('.//xmpp-config'):
    #assert elem.text == 'QA'
    elem.text = 'Prod'

with open(tree, 'w') as file_handle:
    file_handle.write(etree.tostring(tree, pretty_print=True, encoding='utf8'))

<config>
  <logging/>
  <test-mode>false</test-mode>
  <test name="test02">
    <mail/>
    <test-system>0</test-system>
    <system id="0" name="suite1" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="1" name="suite2" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="2" name="suite3" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="3" name="suite4" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
    <system id="4" name="suite5" type="regression">
      <temp-config>Prod</temp-config>
      <rpm>0.5</rpm>
      <cycles>3</cycles>
    </system>
  </test>
</config>

1 个回答

2

在这一行

with open(tree, 'w') as file_handle:

你把 lxml.etree._ElementTree 对象当作文件名传递了。你可能漏掉了一个引号,原本是想要

with open('tree', 'w') as file_handle:

错误信息和追踪信息都很清楚

错误位置: with open(tree, 'w') as file_handle: 所以这和 open 语句有关

错误信息: TypeError: coercing to Unicode: need string or buffer, lxml.etree._ElementTree found

所以看起来我们把 lxml.etree._ElementTree 传给了 open,而不是一个字符串。当然是这样,因为我们传递的 tree 不是字符串,而是 tree = etree.parse('testregression_config.xml'),这是你文件中的第二条语句

撰写回答