Python 3 TypeError:预期使用字符串参数,得到“字节” casperjs_capture

时间:2018-09-26 05:30:51

标签: django python-3.x python-2.7 casperjs

使用python 3执行以下代码时出现错误,但在python 2上运行正常

template_content = <HTML data>
with NamedTemporaryFile(suffix='.html') as render_file:
    render_file.write(template_content.encode('utf-8'))
    render_file.seek(0)
    stream = StringIO()
    casperjs_capture(stream, url='file://%s' % os.path.abspath(render_file.name))

错误:

*** TypeError: string argument expected, got 'bytes'

2 个答案:

答案 0 :(得分:0)

NamedTemporaryFile()返回的文件对象显然处于文本模式,因此在写入template_content之前,请勿将render_file编码为字节。

更改:

render_file.write(template_content.encode('utf-8'))

收件人:

render_file.write(template_content)

答案 1 :(得分:0)

我刚刚从StringIO更改为BytesIO及其对我的工作。要找到解决方案,大约需要一天的时间

template_content = <HTML data>
with NamedTemporaryFile(suffix='.html') as render_file:
    render_file.write(template_content.encode('utf-8'))
    render_file.seek(0)
    stream = BytesIO()
    casperjs_capture(stream, url='file://%s' % os.path.abspath(render_file.name))