无法在urllib2中打开一些仍然可以在浏览器中打开的网址?

时间:2017-02-03 09:31:02

标签: python urllib2

我可以在firefox或chrome中打开此url,但我无法使用urllib2打开它。

>>> req = urllib2.Request(r"http://ratedata.gaincapital.com/2014/.\01 January", headers={'User-Agent' : "Mozilla/5.1"})
>>> urllib2.urlopen(req)

Traceback (most recent call last):
  File "<pyshell#134>", line 1, in <module>
    urllib2.urlopen(req)
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 400: Bad Request

非常奇怪的网址,但我该如何解决?

1 个答案:

答案 0 :(得分:1)

%20

替换空白区域
>>> req = urllib2.Request(r"http://ratedata.gaincapital.com/2014/.\01%20January", headers={'User-Agent' : "Mozilla/5.1"})
>>> urllib2.urlopen(req)
<addinfourl at 139708797193896 whose fp = <socket._fileobject object at 0x7f10820eb2d0>>