SORU
23 EYLÜL 2008, Salı


Nasıl python ile URL normale miyim

Python ile URL normale bilmek istiyorum.

Eğer url bir dize var, örneğin : "http://www.example.com/foo goo/bar.html"

Ekstra boşluk (veya herhangi bir diğer non normalize karakter) uygun bir URL için dönüştürecek python içinde bir kütüphane istiyorum.

CEVAP
23 EYLÜL 2008, Salı


Bu modül bir göz atalım: werkzeug.utils. (şimdi werkzeug.urls)

Aradığınız işlevi "url_fix" ve bu gibi çalışır:

>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)')
'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'

Aşağıdaki gibidir: Werkzeug uygulanmaktadır

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 (Begriffsklärung)'

    :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))

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Excel Video Tutorials

    Excel Video

    6 Aralık 2012
  • Kat Krazy

    Kat Krazy

    12 Kasım 2010
  • MrExcite96

    MrExcite96

    17 ŞUBAT 2011