python2.7 urllib2訪問https 網站出錯
阿新 • • 發佈:2018-11-20
turn text 出錯 default led urllib2 上下 open call 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)>`
今天發現平時每小時報表內容少了好幾個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
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
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:
我把服務器上的代碼拿到本地跑沒問題,但是放到服務器上卻報錯,正是邪門了,百度下,有人遇到過同樣的問題,下面貼出別人的解決方案
`
1. 使用ssl創建未經驗證的上下文,在urlopen中傳入上下文參數
import ssl
import urllib2
context = ssl._create_unverified_context()
print urllib2.urlopen("https://www.12306.cn/mormhweb/", context=context).read()
- 全局取消證書驗證
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
`
我只測試了第一種,代碼該了之後,再服務器上跑了一下,解決問題
python2.7 urllib2訪問https 網站出錯