美文网首页
计算文件的MD5值

计算文件的MD5值

作者: 北游_ | 来源:发表于2018-09-11 11:19 被阅读3次
import requests
import hashlib
import os
import time

def get_file_md5(file_path):
    if os.path.isfile(file_path):
        with open(file_path, 'rb') as f:
            content = f.read()
        md5_obj = hashlib.md5()
        md5_obj.update(str(content).encode(encoding='utf8'))
        hash_code = md5_obj.hexdigest()
        md5 = str(hash_code).lower()
        return md5
    else:
        return None

def crawler_func():
    base_url = 'http://www.baidu.com'
    res = requests.get(base_url)
    if res.status_code == requests.codes.ok:
        print('请求成功')
        file_path = os.path.join(os.path.dirname(os.path.abspath('__file__')), 'index.html')
        with open(file_path, 'w', encoding='utf8') as f:
            f.write(res.text)
        md5_value = get_file_md5(file_path)
        if md5_value:
            print('该文件md5值为{}', md5_value)
        else:
            print('文件md5值计算失败')

if __name__ == "__main__":
    crawler_func()
    time.sleep(3)
    crawler_func()

相关文章

网友评论

      本文标题:计算文件的MD5值

      本文链接:https://www.haomeiwen.com/subject/otoygftx.html