Python 3.x 属性错误:';str';对象没有属性';解码';拉丁语-1
我正在尝试为我的单元测试脚本创建一个HTML报告,当我尝试运行代码时,它抛出了这个错误Python 3.x 属性错误:';str';对象没有属性';解码';拉丁语-1,python-3.x,selenium,selenium-webdriver,Python 3.x,Selenium,Selenium Webdriver,我正在尝试为我的单元测试脚本创建一个HTML报告,当我尝试运行代码时,它抛出了这个错误AttributeError:'str'对象没有属性“decode” 下面是代码的一部分,其中显示错误:- if isinstance(o,str): # TODO: some problem with 'string_escape': it escape \n and mess up formating # uo = unicode(o.encode('string_escape'))
AttributeError:'str'对象没有属性“decode”
下面是代码的一部分,其中显示错误:-
if isinstance(o,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# uo = unicode(o.encode('string_escape'))
uo = o.decode('latin-1')
else:
uo = o
if isinstance(e,str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e.decode('latin-1')
else:
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
)
以上代码来自
htmlestrunner.py
文件。请帮助调试此问题。我假设您正在使用python3(因为您问题中的标记)
python3中不再有unicode
类型,它只是str
-str
是一种文本类型,它已经是unicode解码的,因此,str
不再有decode
方法
对于处理字符串,有一种bytes
类型具有decode
方法(decode
-ingbytes
returnstr
,和encode
-ingstr
返回bytes
)
因此,从现在开始-当类型为str
时,不要使用decode
,而仅当类型为字节时才使用decode
这意味着您的代码应该如下所示:
if isinstance(o,bytes):
uo = o.decode('latin-1')
else:
uo = o
if isinstance(e,bytes):
ue = e.decode('latin-1')
else:
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
)
我假设您正在使用python3(因为您问题中的标签)
python3中不再有unicode
类型,它只是str
-str
是一种文本类型,它已经是unicode解码的,因此,str
不再有decode
方法
对于处理字符串,有一种bytes
类型具有decode
方法(decode
-ingbytes
returnstr
,和encode
-ingstr
返回bytes
)
因此,从现在开始-当类型为str
时,不要使用decode
,而仅当类型为字节时才使用decode
这意味着您的代码应该如下所示:
if isinstance(o,bytes):
uo = o.decode('latin-1')
else:
uo = o
if isinstance(e,bytes):
ue = e.decode('latin-1')
else:
ue = e
script = self.REPORT_TEST_OUTPUT_TMPL % dict(
id = tid,
output = saxutils.escape(uo+ue),
)
正确的方法是decode not encode正确的方法是decode not encode谢谢你帮我Dean,在把它改成“bytes”后,我遇到了一个错误,在“self.stream.write(output.encode('utf8'))一行中,它说,“TypeError:write()参数必须是str,而不是bytes”请帮助我,如何纠正这个问题error@Santosh-在哪一行?这可能发生在这段代码之后,当将报告写入文件时。(它希望用wb
而不是w
)谢谢Dean,它现在开始工作了……:)谢谢您帮助我Dean,在将其更改为“字节”后,我遇到了一个错误,在“self.stream.write(output.encode('utf8'))”一行中,它说,“TypeError:write()参数必须是str,而不是bytes”,请帮助我,如何更正这个错误error@Santosh-在哪一行?在将报告写入文件时,它可能发生在这段代码之后。(它希望用wb
而不是w
)谢谢Dean,它现在开始工作了