首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python 3字节:应为字符串参数,但已获取‘TypeError’casperjs_capture

Python 3字节:应为字符串参数,但已获取‘TypeError’casperjs_capture
EN

Stack Overflow用户
提问于 2018-09-26 13:30:51
回答 2查看 4.2K关注 0票数 2

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

代码语言:javascript
复制
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))

错误:

代码语言:javascript
复制
*** TypeError: string argument expected, got 'bytes'
EN

回答 2

Stack Overflow用户

发布于 2018-09-27 03:31:15

我刚刚完成了从StringIO到BytesIO的更改,它为我工作。要找到解决方案,几乎需要一天的时间。

代码语言:javascript
复制
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))
票数 3
EN

Stack Overflow用户

发布于 2018-09-26 13:42:44

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

更改:

代码语言:javascript
复制
render_file.write(template_content.encode('utf-8'))

至:

代码语言:javascript
复制
render_file.write(template_content)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52510539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档