發生SSL error
今天嘗試著執行Day15的作業, 查詢匯率立即發生以下的錯誤, 看來是SSL連結相關.
我嘗試https改為http, 或是加上headers都無法解決...
是不是漏掉了甚麼呢?
[code]
# 進入台灣銀行牌告匯率網頁,查看當日匯率資料
url = "https://rate.bot.com.tw/xrt?Lang=zh-TW"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
resp = requests.get(url, headers=headers)
resp.encoding = 'utf-8'
# print(resp.text) # 如有需要,列印出網頁原始碼
html = BeautifulSoup(resp.text, "lxml")
rate_table = html.find(name='table', attrs={'title':'牌告匯率'}).find(name='tbody').find_all(name='tr')
# 查詢美金(也就是匯率表的第一個元素)對台幣的匯率
currency = rate_table[0].find(name='div', attrs={'class':'visible-phone print_hide'})
print(currency.get_text().replace(" ", "")) # 去掉空白
buy_rate = rate_table[0].find(name='td', attrs={'data-table':'本行現金買入'})
sell_rate = rate_table[0].find(name='td', attrs={'data-table':'本行現金賣出'})
print("即時現金買入: %s, 即時現金賣出: %s" % (buy_rate.get_text(), sell_rate.get_text()))
[/code]
[error msg]
---------------------------------------------------------------------------
Error Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
455 try:
--> 456 cnx.do_handshake()
457 except OpenSSL.SSL.WantReadError:
C:\Anaconda3\lib\site-packages\OpenSSL\SSL.py in do_handshake(self)
1914 result = _lib.SSL_do_handshake(self._ssl)
-> 1915 self._raise_ssl_error(self._ssl, result)
1916
C:\Anaconda3\lib\site-packages\OpenSSL\SSL.py in _raise_ssl_error(self, ssl, result)
1646 else:
-> 1647 _raise_current_error()
1648
C:\Anaconda3\lib\site-packages\OpenSSL\_util.py in exception_from_error_queue(exception_type)
53
---> 54 raise exception_type(errors)
55
Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]
During handling of the above exception, another exception occurred:
SSLError Traceback (most recent call last)
C:\Anaconda3\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)
599 body=body, headers=headers,
--> 600 chunked=chunked)
601
C:\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _make_request(self, conn, method, url, timeout, chunked, **httplib_request_kw)
342 try:
--> 343 self._validate_conn(conn)
344 except (SocketTimeout, BaseSSLError) as e:
C:\Anaconda3\lib\site-packages\urllib3\connectionpool.py in _validate_conn(self, conn)
838 if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
--> 839 conn.connect()
840
C:\Anaconda3\lib\site-packages\urllib3\connection.py in connect(self)
343 server_hostname=server_hostname,
--> 344 ssl_context=context)
345
C:\Anaconda3\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)
346 if HAS_SNI and server_hostname is not None:
--> 347 return context.wrap_socket(sock, server_hostname=server_hostname)
348
C:\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
461 except OpenSSL.SSL.Error as e:
--> 462 raise ssl.SSLError('bad handshake: %r' % e)
463 break
SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])",)
During handling of the above exception, another exception occurred:
MaxRetryError Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
448 retries=self.max_retries,
--> 449 timeout=timeout
450 )
C:\Anaconda3\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)
637 retries = retries.increment(method, url, error=e, _pool=self,
--> 638 _stacktrace=sys.exc_info()[2])
639 retries.sleep()
C:\Anaconda3\lib\site-packages\urllib3\util\retry.py in increment(self, method, url, response, error, _pool, _stacktrace)
398 if new_retry.is_exhausted():
--> 399 raise MaxRetryError(_pool, url, error or ResponseError(cause))
400
MaxRetryError: HTTPSConnectionPool(host='rate.bot.com.tw', port=443): Max retries exceeded with url: /xrt?Lang=zh-TW (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))
During handling of the above exception, another exception occurred:
SSLError Traceback (most recent call last)
<ipython-input-10-d0590500d4fd> in <module>
4 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
5 }
----> 6 resp = requests.get(url, headers=headers)
7 resp.encoding = 'utf-8'
8 # print(resp.text) # 如有需要,列印出網頁原始碼
C:\Anaconda3\lib\site-packages\requests\api.py in get(url, params, **kwargs)
73
74 kwargs.setdefault('allow_redirects', True)
---> 75 return request('get', url, params=params, **kwargs)
76
77
C:\Anaconda3\lib\site-packages\requests\api.py in request(method, url, **kwargs)
58 # cases, and look like a memory leak in others.
59 with sessions.Session() as session:
---> 60 return session.request(method=method, url=url, **kwargs)
61
62
C:\Anaconda3\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)
531 }
532 send_kwargs.update(settings)
--> 533 resp = self.send(prep, **send_kwargs)
534
535 return resp
C:\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
666
667 # Resolve redirects if allowed.
--> 668 history = [resp for resp in gen] if allow_redirects else []
669
670 # Shuffle things around if there's history.
C:\Anaconda3\lib\site-packages\requests\sessions.py in <listcomp>(.0)
666
667 # Resolve redirects if allowed.
--> 668 history = [resp for resp in gen] if allow_redirects else []
669
670 # Shuffle things around if there's history.
C:\Anaconda3\lib\site-packages\requests\sessions.py in resolve_redirects(self, resp, req, stream, timeout, verify, cert, proxies, yield_requests, **adapter_kwargs)
245 proxies=proxies,
246 allow_redirects=False,
--> 247 **adapter_kwargs
248 )
249
C:\Anaconda3\lib\site-packages\requests\sessions.py in send(self, request, **kwargs)
644
645 # Send the request
--> 646 r = adapter.send(request, **kwargs)
647
648 # Total elapsed time of the request (approximately)
C:\Anaconda3\lib\site-packages\requests\adapters.py in send(self, request, stream, timeout, verify, cert, proxies)
512 if isinstance(e.reason, _SSLError):
513 # This branch is for urllib3 v1.22 and later.
--> 514 raise SSLError(e, request=request)
515
516 raise ConnectionError(e, request=request)
SSLError: HTTPSConnectionPool(host='rate.bot.com.tw', port=443): Max retries exceeded with url: /xrt?Lang=zh-TW (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')])")))
[/error msg]
回答列表
-
2019/12/14 上午 10:05Jeffrey贊同數:0不贊同數:0留言數:2
- 卸載的pyOpenSSL-0.15.1
- 安裝了pyOpenSSL-17.2.0(最新版本
-
2019/12/14 下午 00:27小糖果贊同數:0不贊同數:0留言數:0
-
2019/12/15 下午 05:50張維元 (WeiYuan)贊同數:0不贊同數:0留言數:0
嗨,這個錯誤的原因是比較新的版本中,Python 跟 Request 的安全機制比較嚴格,在請求時會檢查 SSL 驗證。主要有兩種解法:
1. 把驗證關掉(可以參考嘉恩的做法)
2. 安裝 SSL 驗證
```
$ pip install pyOpenSSL
$ pip install -U certifi
```
如果無法安裝的話,可以先更新一下 pip:
```
$ pip install --upgrade pip
```
更多細節可以看這邊:https://stackoverflow.com/questions/27835619/urllib-and-ssl-certificate-verify-failed-error).