如何使用urllib或urllib2对url进行编码

时间:2010-05-15 21:49:00

标签: python urllib2 urllib

我想要像example.com/page.html这样的网址 example.com/a$xDzf9D84qGBOeXkXNstw%3D%3D106

2 个答案:

答案 0 :(得分:3)

如果你的意思是:

  >>> import urllib, base64
  >>> urllib.quote_plus('example.com/page.html')
  'example.com%2Fpage.html'
  >>> base64.urlsafe_b64encode('example.com/page.html')
  'ZXhhbXBsZS5jb20vcGFnZS5odG1s'

答案 1 :(得分:2)

你可能想要这样的东西:

>>> 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'

(请注意,对于带有方案(http://..。)的完整网址,您必须更改第二行)