Python3 error: initial_value must be str or None
在爬取中出现异常,信息如下:
Traceback (most recent call last):
File "***.py", line 10, in <module>
result = Image.open(StringIO(r.content))
TypeError: initial_value must be str or None, not bytes
问题原因:
response.read() returns an instance of bytes while StringIO is an in-memory stream for text only. Use BytesIO instead.
From What's new in Python 3.0 - Text Vs. Data Instead Of Unicode Vs. 8-bit
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
解决方案:
将StringIO替换成BytesIO。
示例如下:
from io import StringIO, BytesIO
def gzipData(data):
buf = BytesIO(data)
f = gzip.GzipFile(fileobj=buf)
return f.read()
还没有评论,来说两句吧...