エラー「SSLCertVerificationError(1, ‘[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate」

問題

Pythonのrequestsを使用していると、以下のようなエラーが出力されてサイトにアクセスできない。

HTTPSConnectionPool(host='ys-holdings.co.jp', port=443): Max retries exceeded with url: /company/profile/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)')))

原因

SSL証明書の認証が行えない場合にエラーとなる。
verify=False を有効にするとアクセス可能になるが、代わりに以下のWarningエラーが出力されて邪魔になる。

C:\Users\aaaaaa\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\connectionpool.py:1043: InsecureRequestWarning: Unverified HTTPS request is being made to host 'www.yamazakipan.co.jp'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#ssl-warnings
  warnings.warn(

対策

以下のようにコードを書くと良い。

import requests
from urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
response = requests.get(url, verify=False)

verify=False を有効にしたうえで、requestsの設定を変えてWarningエラーを抑制する。

コメント

タイトルとURLをコピーしました