pythonpython-requests

Unable to get local issuer certificate when using requests


here is my code

import requests;
url='that website';
headers={
  'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
  'Accept-Language':'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7',
  'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
};
r = requests.get(url,headers=headers);
print(r);
print(r.status_code);

then it ran into this:

requests.exceptions.SSLError:

HTTPSConnectionPool(host='www.xxxxxx.com', port=44 3):

Max retries exceeded with url: xxxxxxxx (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED]

certificate verify failed: unable to get local issuer certificate (_ssl.c:1045)')))

what should i do?


Solution

  • It's not recommended to use verify = False in your organization's environments. This is essentially disabling SSL verification.

    Sometimes, when you are behind a company proxy, it replaces the certificate chain with the ones of Proxy. Adding the certificates in cacert.pem used by certifi should solve the issue. I had similar issue. Here is what I did, to resolve the issue -

    1. Find the path where cacert.pem is located -

    Install certifi, if you don't have. Command: pip install certifi

    import certifi
    certifi.where()
    C:\\Users\\[UserID]\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\certifi\\cacert.pem
    
    1. Open the URL on a browser. Download the chain of certificates from the URL and save as Base64 encoded .cer files.

    2. Now open the cacert.pem in a notepad and just add every downloaded certificate contents (---Begin Certificate--- *** ---End Certificate---) at the end.