Search code examples
pythonurllib2

Python urllib2 unable to open url


I have a URL in this format:

https://aLongStringWithNumbers:anotherLongStringWithNumbers@somewhere.com/admin/someAPICall.json

which looks like not something that Python's urllib2 can understand, keep getting errors when using that with urllib2.open:

raise InvalidURL("nonnumeric port: '%s'" % host[i+1:])

Is this a case where the library is not capable of interpreting that URL? obviously it works in the browser... Using Python 2.7

Any advice would be appreciated! Thanks - V


Solution

  • Python is interpreting the : as the port number in the URL. You need to force it to pull in as a url using something like quote

    See quote from the non-accepted answer here

    >>> import urllib2
    >>> urllib2.quote('https://aLongStringWithNumbers:anotherLongStringWithNumbers@somewhere.com/admin/someAPICall.json')