I want a url like example.com/page.html
to somthing like
example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106
views:
168answers:
2
+1
A:
In case you mean this:
>>> import urllib, base64
>>> urllib.quote_plus('example.com/page.html')
'example.com%2Fpage.html'
>>> base64.urlsafe_b64encode('example.com/page.html')
'ZXhhbXBsZS5jb20vcGFnZS5odG1s'
Tomasz Zielinski
2010-05-15 22:14:02
A:
you probably wanted something like this:
>>> url = 'stackoverflow.com/questions/2841879/how-to-encode-a-url-with-urllib-or-urllib2'
>>> host, path = url.split('/', 1)
>>> path_mangled = ''.join(['%%%02x' % ord(x) if x not in '/?&' else x for x in path])
>>> url_mangled = '/'.join([host, path_mangled])
>>> url_mangled
'stackoverflow.com/%71%75%65%73%74%69%6f%6e%73/%32%38%34%31%38%37%39/%68%6f%77%2d%74%6f%2d%65%6e%63%6f%64%65%2d%61%2d%75%72%6c%2d%77%69%74%68%2d%75%72%6c%6c%69%62%2d%6f%72%2d%75%72%6c%6c%69%62%32'
(note that for full urls with scheme (http://...), you you have to change the second line)
mykhal
2010-05-19 21:16:42