解码URL中的转义字符

Ton*_*ony 73 python escaping

我有一个列表,其中包含带有转义字符的网址.这些字符是urllib2.urlopen在恢复html页面时设置的:

http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=edit
http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&action=history
http://www.sample1webpage.com/index.php?title=%E9%A6%96%E9%A1%B5&variant=zh 
Run Code Online (Sandbox Code Playgroud)

有没有办法在python中将它们转换回未转义的形式?

PS:URL以utf-8编码

Ign*_*ams 126

官方文档.

urllib.unquote()

%xx单字符等效替换转义符.

示例:unquote('/%7Econnolly/')收益率'/~connolly/'.

然后只是解码.


更新: 对于Python 3,请编写以下内容:

urllib.parse.unquote(url)
Run Code Online (Sandbox Code Playgroud)

Python 3文档.

  • 请注意,对于python3,这是`urllib.parse.unquote` (11认同)
  • 对于python3,它也在`urllib.request.unquote`中 (4认同)
  • @dyoser你需要把它放在你的问题中. (3认同)

Vla*_*ruz 25

如果您正在使用,Python3您可以使用:

urllib.parse.unquote(url)
Run Code Online (Sandbox Code Playgroud)


dli*_*dli 9

要么 urllib.unquote_plus

>>> import urllib
>>> urllib.unquote('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29')
'erythrocyte+membrane+protein+1,+PfEMP1+(VAR)'
>>> urllib.unquote_plus('erythrocyte+membrane+protein+1%2C+PfEMP1+%28VAR%29')
'erythrocyte membrane protein 1, PfEMP1 (VAR)'
Run Code Online (Sandbox Code Playgroud)


Kla*_*sen 7

您可以使用 urllib.unquote


小智 6

import re

def unquote(url):
  return re.compile('%([0-9a-fA-F]{2})',re.M).sub(lambda m: chr(int(m.group(1),16)), url)
Run Code Online (Sandbox Code Playgroud)

  • 当有一个内置库可以满足您的需要时,为什么要手动使用正则表达式和 lambdas,甚至可能更周到? (8认同)
  • 很酷的解决方案!`urllib2` 不是标准 python 发行版的一部分。`re` 是。 (7认同)