SSLについては全く分からないので、ご容赦いただければと思います。
よろしくお願いいたします。
エラーメッセージと解決したいこと
Tweepyを使用してTwitter APIからツイートを取得するため、JupyterLab上でツイートの取得を試みました。しかしSSLCertVerificationErrorが表示されるため、ツイートが取得できません。解決方法をご教授いただけますでしょうか。
環境、コード、エラーメッセージは以下の通りです。Twitter APIの利用申請は完了し承認されています。
【環境】
ソフト:JupyterLab(サーバー:Google Chrome)
OS:Windows10
PC:会社支給
接続:自宅からVPN(テレワーク)
【コード】
参考URL:https://qiita.com/kitarikes/items/543ab75a379f0bf903cc
import tweepy consumer_key = "APIから取得したもの" consumer_secret = "APIから取得したもの" access_token = "APIから取得したもの" access_token_secret = "APIから取得したもの" proxy = "http://[ユーザーID]:[パスワード]@[プロキシサーバのアドレス]:[ポート番号]" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, proxy=proxy) q = "teratail" nitems = 5 tweets = tweepy.Cursor(api.search_tweets, q=q, lang="ja").items(nitems) for tweet in tweets: print(tweet)
【エラーメッセージ】
※最大文字数を超えたので、後半部分は補足に追記します。
--------------------------------------------------------------------------- SSLCertVerificationError Traceback (most recent call last) ~\Miniconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw) 695 if is_new_proxy_conn and http_tunnel_required: --> 696 self._prepare_proxy(conn) 697 ~\Miniconda3\lib\site-packages\urllib3\connectionpool.py in _prepare_proxy(self, conn) 963 --> 964 conn.connect() 965 ~\Miniconda3\lib\site-packages\urllib3\connection.py in connect(self) 410 --> 411 self.sock = ssl_wrap_socket( 412 sock=conn, ~\Miniconda3\lib\site-packages\urllib3\util\ssl_.py in ssl_wrap_socket(sock, keyfile, certfile, cert_reqs, ca_certs, server_hostname, ssl_version, ciphers, ssl_context, ca_cert_dir, key_password, ca_cert_data, tls_in_tls) 448 if send_sni: --> 449 ssl_sock = _ssl_wrap_socket_impl( 450 sock, context, tls_in_tls, server_hostname=server_hostname ~\Miniconda3\lib\site-packages\urllib3\util\ssl_.py in _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname) 492 if server_hostname: --> 493 return ssl_context.wrap_socket(sock, server_hostname=server_hostname) 494 else: ~\Miniconda3\lib\ssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, session) 499 # ctx._wrap_socket() --> 500 return self.sslsocket_class._create( 501 sock=sock, ~\Miniconda3\lib\ssl.py in _create(cls, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname, context, session) 1039 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets") -> 1040 self.do_handshake() 1041 except (OSError, ValueError): ~\Miniconda3\lib\ssl.py in do_handshake(self, block) 1308 self.settimeout(None) -> 1309 self._sslobj.do_handshake() 1310 finally: SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131) During handling of the above exception, another exception occurred: MaxRetryError Traceback (most recent call last) ~\Miniconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies) 438 if not chunked: --> 439 resp = conn.urlopen( 440 method=request.method, ~\Miniconda3\lib\site-packages\urllib3\connectionpool.py in urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, **response_kw) 754 --> 755 retries = retries.increment( 756 method, url, error=e, _pool=self, _stacktrace=sys.exc_info()[2] ~\Miniconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace) 573 if new_retry.is_exhausted(): --> 574 raise MaxRetryError(_pool, url, error or ResponseError(cause)) 575 MaxRetryError: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/search/tweets.json?q=teratail&lang=ja (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)'))) During handling of the above exception, another exception occurred: SSLError Traceback (most recent call last) ~\Miniconda3\lib\site-packages\tweepy\api.py in request(self, method, endpoint, endpoint_parameters, params, headers, json_payload, parser, payload_list, payload_type, post_data, files, require_auth, return_cursors, upload_api, use_cache, **kwargs) 215 try: --> 216 resp = self.session.request( 217 method, url, params=params, headers=headers, ~\Miniconda3\lib\site-packages\requests\sessions.py in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json) 541 send_kwargs.update(settings) --> 542 resp = self.send(prep, **send_kwargs) 543 ~\Miniconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs) 654 # Send the request --> 655 r = adapter.send(request, **kwargs) 656 ~\Miniconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies) 513 # This branch is for urllib3 v1.22 and later. --> 514 raise SSLError(e, request=request) 515 SSLError: HTTPSConnectionPool(host='api.twitter.com', port=443): Max retries exceeded with url: /1.1/search/tweets.json?q=teratail&lang=ja (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1131)'))) During handling of the above exception, another exception occurred: TweepyException Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_13316/2438765585.py in <module> 16 tweets = tweepy.Cursor(api.search_tweets, q=q, lang="ja").items(nitems) 17 ---> 18 for tweet in tweets: 19 print(tweet) ~\Miniconda3\lib\site-packages\tweepy\cursor.py in __next__(self) 84 85 def __next__(self): ---> 86 return self.next() 87 88 def next(self): ~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self) 284 if self.current_page is None or self.page_index == len(self.current_page) - 1: 285 # Reached end of current page, get the next page... --> 286 self.current_page = next(self.page_iterator) 287 while len(self.current_page) == 0: 288 self.current_page = next(self.page_iterator) ~\Miniconda3\lib\site-packages\tweepy\cursor.py in __next__(self) 84 85 def __next__(self): ---> 86 return self.next() 87 88 def next(self): ~\Miniconda3\lib\site-packages\tweepy\cursor.py in next(self) 165 166 if self.index >= len(self.results) - 1: --> 167 data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kwargs) 168 169 model = ModelParser().parse( ~\Miniconda3\lib\site-packages\tweepy\api.py in wrapper(*args, **kwargs) 31 @functools.wraps(method) 32 def wrapper(*args, **kwargs): ---> 33 return method(*args, **kwargs) 34 wrapper.pagination_mode = mode 35 return wrapper ~\Miniconda3\lib\site-packages\tweepy\api.py in wrapper(*args, **kwargs) 44 kwargs['payload_list'] = payload_list 45 kwargs['payload_type'] = payload_type ---> 46 return method(*args, **kwargs) 47 wrapper.payload_list = payload_list 48 wrapper.payload_type = payload_type ~\Miniconda3\lib\site-packages\tweepy\api.py in search_tweets(self, q, **kwargs) 1266 https://developer.twitter.com/en/docs/twitter-api/v1/tweets/search/api-reference/get-search-tweets 1267 """ -> 1268 return self.request( 1269 'GET', 'search/tweets', endpoint_parameters=( 1270 'q', 'geocode', 'lang', 'locale', 'result_type', 'count', ~\Miniconda3\lib\site-packages\tweepy\api.py in request(self, method, endpoint, endpoint_parameters, params, headers, json_payload, parser, payload_list, payload_type, post_data, files, require_auth, return_cursors, upload_api, use_cache, **kwargs) 220 ) 221 except Exception as e: --> 222 raise TweepyException(f'Failed to send request: {e}').with_traceback(sys.exc_info()[2]) 223 224 if 200 <= resp.status_code < 300:
解決法についてのお願い
おそらく以下のコードでSSLサーバ証明書の検証を無効にすれば取得できるかと思いますが、セキュリティの関係上使用したくないと考えています(Twitter APIにもSSLが必要と書いてあるので、それを無視するのは良くないとも思います)。
そのため、SSLの検証が通るような方法をご教授いただけますでしょうか。
【使用したくないコード】
参考URL:https://qiita.com/hrappuccino/items/84e3a5113b871037024a
import os os.environ["CURL_CA_BUNDLE"] = ""
その他
・Twitter APIのkey、プロキシの設定は間違っていないと思います。
・会社のPCからGoogle Chromeで、Twitterにログインは可能です。
よろしくお願いいたします。

回答2件
あなたの回答
tips
プレビュー