如何在 python 中规范化 URL [英] How can I normalize a URL in python

查看:82
本文介绍了如何在 python 中规范化 URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我是否在 python 中规范化了一个 URL.

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

我需要一个 Python 库来将多余的空间(或任何其他非规范化字符)转换为正确的 URL.

解决方案

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

您要查找的函数称为url_fix",其工作方式如下:

<预><代码>>>>从 werkzeug.urls 导入 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 中的实现如下:

导入urllib导入 urlparsedef url_fix(s, charset='utf-8'):"""有时你会得到一个用户提供的 URL,但它并不是真实的URL,因为它包含不安全的字符,如 ' ' 等.这功能可以以类似的方式修复浏览器的一些问题处理用户输入的数据:>>>url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29':param charset: URL 的目标字符集,如果 url 是作为 unicode 字符串给出."""如果 isinstance(s, unicode):s = s.encode(charset, '忽略')方案,netloc,路径,qs,anchor = urlparse.urlsplit(s)path = urllib.quote(path, '/%')qs = urllib.quote_plus(qs, ':&=')return urlparse.urlunsplit((scheme, netloc, path, qs, anchor))

I'd like to know do I normalize a URL in python.

For example, If I have a url string like : "http://www.example.com/foo goo/bar.html"

I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.

解决方案

Have a look at this module: werkzeug.utils. (now in werkzeug.urls)

The function you are looking for is called "url_fix" and works like this:

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

It's implemented in Werkzeug as follows:

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 中规范化 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆