python urllib2

import urllib2

req=urllib2.Request('https://xxxx')

resp=urllib2.urlopen(req)

>>> resp=urllib2.urlopen(req)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  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)
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>


>>> import ssl
>>> context=ssl._create_unverified_context()
>>> resp=urllib2.urlopen(req,context=context)

解决ssl 问题

 

>>> resp=urllib2.urlopen(req,context=context)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  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 437, in open
    response = meth(req, response)
  File "/usr/local/lib/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/lib/python2.7/urllib2.py", line 475, in error
    return self._call_chain(*args)
  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 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 401: Authorization Required

auth = encodestring('%s:%s'%(username,password))[:-1]
#print auth
req.add_header('Authorization', 'Basic %s'%auth)

resp=urllib2.urlopen(req,context=context)

或者

req=urllib2.Request('https://xxxx',headers={'Authorization':'Basic %s'%auth})

resp=urllib2.urlopen(req,context=context)

 

 

完整代码

import urllib2
from base64 import encodestring
import ssl

username='xxx'
password='xxxx'

auth = encodestring('%s:%s'%(username,password))[:-1]

req=urllib2.Request('https:/xxxx',headers={'Authorization':'Basic %s'%auth})

context=ssl._create_unverified_context()

resp=urllib2.urlopen(req,context=context)

 

 

 

 

posted @ 2019-11-19 16:04  nevermore_29  阅读(186)  评论(0编辑  收藏  举报