Python3 error: initial_value must be str or None

川长思鸟来 2022-05-28 23:26 417阅读 0赞

在爬取中出现异常,信息如下:

  1. Traceback (most recent call last):
  2. File "***.py", line 10, in <module>
  3. result = Image.open(StringIO(r.content))
  4. TypeError: initial_value must be str or None, not bytes

问题原因:

  1. response.read() returns an instance of bytes while StringIO is an in-memory stream for text only. Use BytesIO instead.
  2. From What's new in Python 3.0 - Text Vs. Data Instead Of Unicode Vs. 8-bit
  3. 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。
示例如下:

  1. from io import StringIO, BytesIO
  2. def gzipData(data):
  3. buf = BytesIO(data)
  4. f = gzip.GzipFile(fileobj=buf)
  5. return f.read()

发表评论

表情:
评论列表 (有 0 条评论,417人围观)

还没有评论,来说两句吧...

相关阅读