python - 如何在 python 中规范化 URL

标签 python url normalization normalize

我想知道我是否在 python 中规范化 URL。

例如,如果我有一个 url 字符串,例如:“http://www.example.com/foo goo/bar.html”

我需要一个 python 库,它将额外的空间(或任何其他非规范化字符)转换为正确的 URL。

最佳答案

看看这个模块:werkzeug.utils . (现在在 werkzeug.urls)

您要查找的函数名为“url_fix”,其工作原理如下:

>>> from werkzeug.urls import url_fix
>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'

在 Werkzeug 中实现如下:

import urllib
import urlparse

def url_fix(s, charset='utf-8'):
    """Sometimes you get an URL by a user that just isn't a real
    URL because it contains unsafe characters like ' ' and so on.  This
    function can fix some of the problems in a similar way browsers
    handle data entered by the user:

    >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
    'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'

    :param charset: The target charset for the URL if the url was
                    given as unicode string.
    """
    if isinstance(s, unicode):
        s = s.encode(charset, 'ignore')
    scheme, netloc, path, qs, anchor = urlparse.urlsplit(s)
    path = urllib.quote(path, '/%')
    qs = urllib.quote_plus(qs, ':&=')
    return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))

关于python - 如何在 python 中规范化 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/120951/

相关文章:

python - 如何定义 `for` 语句中的变量?

python - Seaborn regplot 使用 datetime64 作为 x 轴

python - Keyerror 多索引数据框 pandas

python - 并行磁盘 I/O

javascript - 如何从 jquery 哈希中获取多个值

azure - 确定 appService、blob 和常规存储的 Azure IP 地址

java - 将 www 保留在 url 中以匹配仅 tomcat 环境中的证书域

mysql - 如何规范化表列中的逗号分隔值然后运行查询

database - 第三范式算法

python - 如何将数据转换为正态分布