public
Last active

urlnorm.py: URL normalisation

  • Download Gist
urlnorm.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
#!/usr/bin/env python
 
"""
urlnorm.py - URL normalisation routines
 
urlnorm normalises a URL by;
* lowercasing the scheme and hostname
* taking out default port if present (e.g., http://www.foo.com:80/)
* collapsing the path (./, ../, etc)
* removing the last character in the hostname if it is '.'
* unquoting any %-escaped characters
 
Available functions:
norms - given a URL (string), returns a normalised URL
norm - given a URL tuple, returns a normalised tuple
test - test suite
CHANGES:
0.92 - unknown schemes now pass the port through silently
0.91 - general cleanup
- changed dictionaries to lists where appropriate
- more fine-grained authority parsing and normalisation
"""
 
__license__ = """
Copyright (c) 1999-2002 Mark Nottingham <mnot@pobox.com>
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
 
__version__ = "0.93"
 
from urlparse import urlparse, urlunparse
from urllib import unquote
from string import lower
import re
 
_collapse = re.compile('([^/]+/\.\./?|/\./|//|/\.$|/\.\.$)')
_server_authority = re.compile('^(?:([^\@]+)\@)?([^\:]+)(?:\:(.+))?$')
_default_port = { 'http': '80',
'https': '443',
'gopher': '70',
'news': '119',
'snews': '563',
'nntp': '119',
'snntp': '563',
'ftp': '21',
'telnet': '23',
'prospero': '191',
}
_relative_schemes = [ 'http',
'https',
'news',
'snews',
'nntp',
'snntp',
'ftp',
'file',
''
]
_server_authority_schemes = [ 'http',
'https',
'news',
'snews',
'ftp',
]
 
 
def norms(urlstring):
"""given a string URL, return its normalised form"""
return urlunparse(norm(urlparse(urlstring)))
 
 
def norm(urltuple):
"""given a six-tuple URL, return its normalised form"""
(scheme, authority, path, parameters, query, fragment) = urltuple
scheme = lower(scheme)
if authority:
userinfo, host, port = _server_authority.match(authority).groups()
if host[-1] == '.':
host = host[:-1]
authority = lower(host)
if userinfo:
authority = "%s@%s" % (userinfo, authority)
if port and port != _default_port.get(scheme, None):
authority = "%s:%s" % (authority, port)
if scheme in _relative_schemes:
last_path = path
while 1:
path = _collapse.sub('/', path, 1)
if last_path == path:
break
last_path = path
path = unquote(path)
return (scheme, authority, path, parameters, query, fragment)
 
 
 
def test():
""" test suite; some taken from RFC1808. """
tests = {
'/foo/bar/.': '/foo/bar/',
'/foo/bar/./': '/foo/bar/',
'/foo/bar/..': '/foo/',
'/foo/bar/../': '/foo/',
'/foo/bar/../baz': '/foo/baz',
'/foo/bar/../..': '/',
'/foo/bar/../../': '/',
'/foo/bar/../../baz': '/baz',
'/foo/bar/../../../baz': '/../baz',
'/foo/bar/../../../../baz': '/baz',
'/./foo': '/foo',
'/../foo': '/../foo',
'/foo.': '/foo.',
'/.foo': '/.foo',
'/foo..': '/foo..',
'/..foo': '/..foo',
'/./../foo': '/../foo',
'/./foo/.': '/foo/',
'/foo/./bar': '/foo/bar',
'/foo/../bar': '/bar',
'/foo//': '/foo/',
'/foo///bar//': '/foo/bar/',
'http://www.foo.com:80/foo': 'http://www.foo.com/foo',
'http://www.foo.com:8000/foo': 'http://www.foo.com:8000/foo',
'http://www.foo.com./foo/bar.html': 'http://www.foo.com/foo/bar.html',
'http://www.foo.com.:81/foo': 'http://www.foo.com:81/foo',
'http://www.foo.com/%7ebar': 'http://www.foo.com/~bar',
'http://www.foo.com/%7Ebar': 'http://www.foo.com/~bar',
'ftp://user:pass@ftp.foo.net/foo/bar': 'ftp://user:pass@ftp.foo.net/foo/bar',
'http://USER:pass@www.Example.COM/foo/bar': 'http://USER:pass@www.example.com/foo/bar',
'http://www.example.com./': 'http://www.example.com/',
'-': '-',
}
 
n_correct, n_fail = 0, 0
test_keys = tests.keys()
test_keys.sort()
for i in test_keys:
print 'ORIGINAL:', i
cleaned = norms(i)
answer = tests[i]
print 'CLEANED: ', cleaned
print 'CORRECT: ', answer
if cleaned != answer:
print "*** TEST FAILED"
n_fail = n_fail + 1
else:
n_correct = n_correct + 1
print
print "TOTAL CORRECT:", n_correct
print "TOTAL FAILURE:", n_fail
 
 
if __name__ == '__main__':
test()

Very usefull piece of code, i am trying to prse some URLs and sometimes is painfull.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.