写了一个hash 报错这是为啥

Traceback (most recent call last):
  File "/home/shenjianlin/.local/lib/python3.4/site-packages/twisted/internet/defer.py", line 653, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File "/home/shenjianlin/my_project/Espider/Espider/pipelines/searchwebsitepipeline.py", line 37, in process_item
    iconUrl=self.get_max_size_url(item['iconUrl'])
  File "/home/shenjianlin/my_project/Espider/Espider/pipelines/searchwebsitepipeline.py", line 18, in get_max_size_url
    save_path = os.path.join("./image", hashlib.sha1(res.content))
  File "/usr/lib64/python3.4/posixpath.py", line 79, in join
    if b.startswith(sep):
AttributeError: '_hashlib.HASH' object has no attribute 'startswith'### 题目描述


阅读 2.3k
2 个回答

类型不正确.
os.path.join 期待传入一个字符串类型的参数, 而你这里传入了一个_hashlib.HASH类型的对象.

>>> import hashlib
>>> hashlib.sha1(b'this is plaintext')
<sha1 HASH object @ 0x7f0a100539e0>

我估计你是想获取HASH的 16 进制结果.可以用hexdigest方法, 就像这样:

>>> print(hashlib.sha1(b'this is plaintext').hexdigest())
29487b3263304dba8c04fbe1169a8b8044e0bf8e

或者返回 Bytes 类型, 然后再转码(不推荐):

>>> print(hashlib.sha1(b'this is plaintext').digest())
b')H{2c0M\xba\x8c\x04\xfb\xe1\x16\x9a\x8b\x80D\xe0\xbf\x8e'

参考:
python hashlib doc

推荐问题