[英]How do I disable the ssl check in python 3.x?
我正在使用 urllib.request.urlretrieve 将文件下载到本地。
urllib.request.urlretrieve(url_string,file_name)
它抛出错误:
ssl.CertificateError 未由用户代码处理 消息:主机名“foo.net”与“a248.e.akamai.net”、“. akamaihd.net”、“ . akamaihd-staging.net”、“中的任一个都不匹配” 。 akamaized.net', ' .akamaized-staging.net'
如果您将网址复制到 Chrome 中,它会向您显示一条通知,您需要说“继续访问该网址”之类的内容。
将urllib.request.urlopen
与自定义 ssl 上下文一起使用:
import ssl
import urllib.request
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
with urllib.request.urlopen(url_string, context=ctx) as u, \
open(file_name, 'wb') as f:
f.write(u.read())
或者,如果您使用requests
库,它可能会更简单:
import requests
with open(file_name, 'wb') as f:
resp = requests.get(url_string, verify=False)
f.write(resp.content)
函数urllib.request.urlretrieve
不接受任何 SSL 选项,但urllib.request.urlopen
接受。
但是,使用ssl.create_default_context()
创建安全的 SSL 上下文并使其不安全,您可以使用ssl.SSLContext()
创建不安全的上下文:
这个:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
相当于:
ctx = ssl.SSLContext()
(对于 Python < 3.5.3 使用ssl.SSLContext(ssl.PROTOCOL_TLSv1)
)
这使得一个很好的单线:
import ssl
import urllib.request
with urllib.request.urlopen("https://wrong.host.badssl.com/", context=ssl.SSLContext()) as url:
print(url.read())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.