1. 程式人生 > >python2.7 urllib2訪問https 網站出錯

python2.7 urllib2訪問https 網站出錯

     今天發現平時每小時報表內容少了好幾個table ,感覺好奇怪,這個程式碼很穩定跑了好長時間了,不知道哪裡出來問題,幸虧程式碼做了異常處理。否則我估計郵件都會發不出來了,看了下日誌檔案,有報錯日誌記錄如下:
             `  page = urllib2.urlopen(url, timeout=300)

File "/usr/local/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python2.7/urllib2.py", line 431, in open
response = self._open(req, data)
File "/usr/local/lib/python2.7/urllib2.py", line 449, in _open
'_open', req)
File "/usr/local/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/usr/local/lib/python2.7/urllib2.py", line 1240, in https_open
context=self._context)
File "/usr/local/lib/python2.7/urllib2.py", line 1197, in do_open
raise URLError(err)
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>
2018-11-13 07:03:27,612 - <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:
581)>
2018-11-13 08:03:10,058 - <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:
581)>`

我把伺服器上的程式碼拿到本地跑沒問題,但是放到伺服器上卻報錯,正是邪門了,百度下,有人遇到過同樣的問題,下面貼出別人的解決方案

 `
 1. 使用ssl建立未經驗證的上下文,在urlopen中傳入上下文引數

import ssl
import urllib2

context = ssl._create_unverified_context()
print urllib2.urlopen("https://www.12306.cn/mormhweb/", context=context).read()

  1. 全域性取消證書驗證
    import ssl
    import urllib2

ssl._create_default_https_context = ssl._create_unverified_context

print urllib2.urlopen("https://www.12306.cn/mormhweb/").read()
注意:在全全域性請求檔案匯入import ssl
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
`

 我只測試了第一種,程式碼該了之後,再伺服器上跑了一下,解決問題