【问题标题】:Python 3 TypeError: string argument expected, got 'bytes' casperjs_capturePython 3 TypeError:需要字符串参数,得到 'bytes' casperjs_capture
【发布时间】:2019-03-01 19:22:37
【问题描述】:

使用 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'

【问题讨论】:

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


    【解决方案1】:

    我刚刚从 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))
    

    【讨论】:

      【解决方案2】:

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

      变化:

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

      到:

      render_file.write(template_content)
      

      【讨论】:

        猜你喜欢
        • 2020-11-04
        • 2015-10-30
        • 1970-01-01
        • 2018-05-18
        • 1970-01-01
        • 2021-05-10
        • 2019-10-16
        • 1970-01-01
        • 2013-04-07
        相关资源
        最近更新 更多