views:

4034

answers:

6

I'd like to know do I normalize a URL in python.

For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"

I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.

+5  A: 
import urlparse, urllib
def myquote(url):
    parts= urlparse.urlparse(url)
    return urlparse.urlunparse(parts[:2] + urllib.quote(parts[2]) + parts[3:])

This quotes only the path component.

Otherwise, you could do: urllib.quote(url, safe=":/")

ΤΖΩΤΖΙΟΥ
That just quote all characters. That won't help him.
Armin Ronacher
In this example, it would also quote the ':' character (not all). Thanks for the comment.
ΤΖΩΤΖΙΟΥ
+11  A: 

use urllib.quote or urllib.quote_plus

From the urllib documentation:

quote(string[, safe])

Replace special characters in string using the "%xx" escape. Letters, digits, and the characters "_.-" are never quoted. The optional safe parameter specifies additional characters that should not be quoted -- its default value is '/'.

Example: quote('/~connolly/') yields '/%7econnolly/'.

quote_plus(string[, safe])

Like quote(), but also replaces spaces by plus signs, as required for quoting HTML form values. Plus signs in the original string are escaped unless they are included in safe. It also does not have safe default to '/'.

EDIT: Using urllib.quote or urllib.quote_plus on the whole URL will mangle it, as @ΤΖΩΤΖΙΟΥ points out:

>>> quoted_url = urllib.quote('http://www.example.com/foo goo/bar.html')
>>> quoted_url
'http%3A//www.example.com/foo%20goo/bar.html'
>>> urllib2.urlopen(quoted_url)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\python25\lib\urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "c:\python25\lib\urllib2.py", line 373, in open
    protocol = req.get_type()
  File "c:\python25\lib\urllib2.py", line 244, in get_type
    raise ValueError, "unknown url type: %s" % self.__original
ValueError: unknown url type: http%3A//www.example.com/foo%20goo/bar.html

@ΤΖΩΤΖΙΟΥ provides a function that uses urlparse.urlparse and urlparse.urlunparse to parse the url and only encode the path. This may be more useful for you, although if you're building the URL from a known protocol and host but with a suspect path, you could probably do just as well to avoid urlparse and just quote the suspect part of the URL, concatenating with known safe parts.

Blair Conrad
So, what does urllib.quote return given the question's example url?
ΤΖΩΤΖΙΟΥ
Garbage. Why is an obviously wrong answer accepted as solution?
Armin Ronacher
@ΤΖΩΤΖΙΟΥ: excellent point. Addressed@Armin Ronacher: possibly because the answerer and accepter weren't aware of the problem - not all problems are obvious to all.
Blair Conrad
suggested edit: "…and only encode the hostname" → "…and only quote the path"
ΤΖΩΤΖΙΟΥ
Of course, @ΤΖΩΤΖΙΟΥ . Thanks! Sometimes I don't know where I leave my brain.
Blair Conrad
+10  A: 

Have a look at this module: werkzeug.utils.

The function you are looking for is called "url_fix" and works like this:

>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'

It's implemented in Werkzeug as follows:

import urllib
import urlparse

def url_fix(s, charset='utf-8'):
    """Sometimes you get an URL by a user that just isn't a real
    URL because it contains unsafe characters like ' ' and so on.  This
    function can fix some of the problems in a similar way browsers
    handle data entered by the user:

    >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
    'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'

    :param charset: The target charset for the URL if the url was
                    given as unicode string.
    """
    if isinstance(s, unicode):
        s = s.encode(charset, 'ignore')
    scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
    path = urllib.quote(path, '/%')
    qs = urllib.quote_plus(qs, ':&=')
    return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))
Armin Ronacher
While this is from a http rfc2616 probably the more accurate solution, I think it's overkill, or do I miss something?
Florian Bösch
Yes. You probably missed the question. He has an URL from user input and wants to properly convert it into a real URL. (Aka: do what the firefox location bar does)
Armin Ronacher
+5  A: 

Real fix in Python 2.7 for that problem

Right solution was:

 # percent encode url, fixing lame server errors for e.g, like space
 # within url paths.
 fullurl = quote(fullurl, safe="%/:=&?~#+!$,;'@()*[]")

For more information see Issue918368: "urllib doesn't correct server returned urls"

Oleg Sakharov
+6  A: 

Because this page is a top result for Google searches on the topic, I think it's worth mentioning some work that has been done on URL normalization with Python that goes beyond urlencoding space characters. For example, dealing with default ports, character case, lack of trailing slashes, etc.

When the Atom syndication format was being developed, there was some discussion on how to normalize URLs into canonical format; this is documented in the article PaceCanonicalIds on the Atom/Pie wiki. That article provides some good test cases.

I believe that one result of this discussion was Mark Nottingham's urlnorm.py library, which I've used with good results on a couple projects. That script doesn't work with the URL given in this question, however. So a better choice might be Sam Ruby's version of urlnorm.py, which handles that URL, and all of the aforementioned test cases from the Atom wiki.

cobra libre
+2  A: 

Just FYI, urlnorm has moved to github: http://gist.github.com/246089

Mark Nottingham