开发者

how to encode a url with urllib or urllib2

开发者 https://www.devze.com 2022-12-31 10:41 出处:网络
I want a url like example.com/page.html to somthing like example.com/a$xDzf9D84qGBOeXkXNstw开发者_Go百科%3D%3D106In case you mean this:

I want a url like example.com/page.html to somthing like example.com/a$xDzf9D84qGBOeXkXNstw开发者_Go百科%3D%3D106


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'


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消