MacOS下urllib.request.urlopen()报CERTIFICATE_VERIFY_FAILED错误求助
Hey there, I see you're hitting that annoying SSL certificate error on your Mac while using Python 3.6.5's urllib module, even though the same code works fine on repl.it. Let's break down why this happens and fix it.
Why this happens
The root issue here is that the Python 3.6.5 installed on your Mac (likely via the official installer) doesn't have the system's root certificates properly configured. Repl.it runs in a pre-setup environment where these certificates are already configured, which is why your code works there without a hitch.
Solutions to try
Fix 1: Install missing root certificates (recommended)
The official Python installer for Mac includes a dedicated script to resolve this certificate issue. Open your Terminal and run this command:/Applications/Python\ 3.6/Install\ Certificates.commandThis script will fetch and install the necessary root certificates, allowing urllib to verify SSL connections correctly going forward.
Fix 2: Temporarily bypass certificate verification (for testing only)
If you just need to test your code quickly and don't mind skipping security checks for this specific case, you can modify your code to disable certificate verification:import urllib.request import ssl # Create an SSL context that skips certificate checks ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE req = urllib.request.urlopen('http://www.pythonprogramming.net', context=ctx) print(req.read())Important: Never use this in production! Disabling verification exposes you to potential man-in-the-middle attacks.
Fix 3: Upgrade your Python version
Python 3.6 has reached its end-of-life, meaning it no longer receives security updates or bug fixes. Upgrading to a newer, supported version (like 3.8 or later) will not only resolve this certificate problem but also give you access to newer language features and improved security. You can use a version manager like pyenv to easily manage multiple Python versions on your Mac, or download the latest installer from the official Python site.
内容的提问来源于stack exchange,提问作者Ramanujan

