把二进制文件写入文件
1 # -*- coding: utf-8 -*- 2 """ 3 Created on Tue Apr 7 14:46:11 2020 4 5 @author: ZKYAAA 6 """ 7 import urllib.request 8 9 pic_url="http://www.baidu.com/img/bd_logo1.png" 10 pic_resp=urllib.request.urlopen(pic_url) 11 pic=pic_resp.read() 12 with open("bd_logo1.png","wb")as f: 13 f.write(pic) 14 15 #还可以调用 urllib.request.urlretrieve()函数直接进行下载 16 urllib.request.urlretrieve(pic_url,'bd_logo.png')
如入出现错误
... urllib.error.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)>
解决方法
1 import ssl 2 # 方法一:全局取消证书验证 3 ssl._create_default_https_context = ssl._create_unverified_context 4 # 方法二:使用ssl创建未经验证的上下文,在urlopen()中传入上下文参数 5 context = ssl._create_unverified_context() 6 pic_resp = urllib.request.urlopen(pic_url,context=context)