Python9 मिनट का पठन

Python में URL Encode कैसे करें (urllib.parse की संपूर्ण गाइड)

Python में URL encoding के लिए strings को percent-encode करने हेतु urllib.parse.quote() और dictionaries को query strings में बदलने हेतु urllib.parse.urlencode() का उपयोग होता है। यह गाइड quote(), unquote(), urlencode() और parse_qs() को व्यावहारिक उदाहरणों के साथ समझाती है।

quote() के साथ URL Encoding

urllib.parse.quote() फ़ंक्शन strings को percent-encode करने के लिए Python का प्रमुख उपकरण है। यह उन अक्षरों को, जो URLs में उपयोग के लिए सुरक्षित नहीं हैं, उनके percent-encoded रूप में बदल देता है। डिफ़ॉल्ट रूप से यह forward slashes (/) को सुरक्षित अक्षर मानता है, लेकिन आप इस व्यवहार को अनुकूलित कर सकते हैं।

from urllib.parse import quote

# बुनियादी encoding
print(quote('hello world'))
# Output: hello%20world

# विशेष अक्षरों की encoding
print(quote('price=10&qty=2'))
# Output: price%3D10%26qty%3D2

# डिफ़ॉल्ट रूप से, / को encode नहीं किया जाता
print(quote('path/to/file'))
# Output: path/to/file

# slashes को भी encode करने के लिए, safe='' सेट करें
print(quote('path/to/file', safe=''))
# Output: path%2Fto%2Ffile

# Unicode अक्षरों की encoding
print(quote('cafe'))
# Output: caf%C3%A9

# अतिरिक्त सुरक्षित अक्षर निर्दिष्ट करना
print(quote('key=value&foo=bar', safe='=&'))
# Output: key=value&foo=bar

safe पैरामीटर ही यह नियंत्रित करने की कुंजी है कि क्या encode किया जाएगा। डिफ़ॉल्ट रूप से safe='/' होता है। यदि आप alphanumeric अक्षरों और _.-~ को छोड़कर बाकी सब कुछ encode करना चाहते हैं, तो safe='' सेट करें। यह JavaScript के encodeURIComponent() के समतुल्य है।

एक quote_plus() भी है जो quote() की तरह ही काम करता है, लेकिन spaces को %20 के बजाय + के रूप में encode करता है। यही प्रारूप HTML form data (application/x-www-form-urlencoded) में उपयोग होता है।

from urllib.parse import quote_plus

print(quote_plus('hello world'))
# Output: hello+world

print(quote_plus('key=value&name=John Doe'))
# Output: key%3Dvalue%26name%3DJohn+Doe

unquote() के साथ URL Decoding

urllib.parse.unquote() फ़ंक्शन percent-encoding को उलट देता है, यानी %XX अनुक्रमों को उनके मूल अक्षरों में वापस बदल देता है। एक unquote_plus() भी है जो इसके अतिरिक्त + चिह्नों को spaces में बदल देता है।

from urllib.parse import unquote, unquote_plus

# बुनियादी decoding
print(unquote('hello%20world'))
# Output: hello world

print(unquote('caf%C3%A9'))
# Output: cafe (उच्चारण चिह्न के साथ)

# unquote, + को space में परिवर्तित नहीं करता
print(unquote('hello+world'))
# Output: hello+world

# unquote_plus, + को space में परिवर्तित करता है
print(unquote_plus('hello+world'))
# Output: hello world

# पूरे URL को decode करना
url = 'https://example.com/search?q=C%2B%2B%20programming'
print(unquote(url))
# Output: https://example.com/search?q=C++ programming

form data को decode करते समय हमेशा unquote_plus() का उपयोग करें, क्योंकि HTML forms spaces को + के रूप में encode करते हैं। सामान्य URL decoding के लिए, जहाँ spaces %20 के रूप में encode होते हैं, unquote() का उपयोग करें।

urlencode() के साथ Query Strings की Encoding

urllib.parse.urlencode() फ़ंक्शन एक dictionary या tuples की सूची लेता है और उसे एक सही ढंग से स्वरूपित query string में बदल देता है। Python में query strings बनाने का यह सबसे सुविधाजनक तरीका है।

from urllib.parse import urlencode

# Dictionary से query string
params = {
    'q': 'python programming',
    'page': 1,
    'lang': 'en'
}
print(urlencode(params))
# Output: q=python+programming&page=1&lang=en

# Tuples की सूची (क्रम बनाए रखती है, डुप्लिकेट keys की अनुमति देती है)
params = [
    ('tag', 'python'),
    ('tag', 'web'),
    ('sort', 'date')
]
print(urlencode(params))
# Output: tag=python&tag=web&sort=date

# सूची मानों के लिए doseq=True का उपयोग
params = {
    'tag': ['python', 'web', 'api'],
    'sort': 'date'
}
print(urlencode(params, doseq=True))
# Output: tag=python&tag=web&tag=api&sort=date

# space की encoding को नियंत्रित करने के लिए quote_via का उपयोग
from urllib.parse import quote
params = {'q': 'hello world'}
print(urlencode(params, quote_via=quote))
# Output: q=hello%20world  (+ के बजाय %20 का उपयोग करता है)

डिफ़ॉल्ट रूप से urlencode() अंदरूनी तौर पर quote_plus() का उपयोग करता है, जिसका अर्थ है कि spaces + बन जाते हैं। यदि आपको spaces के लिए %20 चाहिए, तो ऊपर दिखाए अनुसार quote_via=quote पास करें।

parse_qs() के साथ Query Strings की Parsing

urllib.parse.parse_qs() फ़ंक्शन एक query string को वापस एक dictionary में parse करता है। dictionary में प्रत्येक मान एक सूची होता है, क्योंकि query parameters के कई मान हो सकते हैं। एक parse_qsl() भी है जो tuples की सूची लौटाता है।

from urllib.parse import parse_qs, parse_qsl

# एक query string को dictionary में parse करें
qs = 'q=python+programming&page=1&lang=en'
result = parse_qs(qs)
print(result)
# Output: {'q': ['python programming'], 'page': ['1'], 'lang': ['en']}

# ध्यान दें: मान हमेशा सूचियाँ होते हैं
print(result['q'][0])  # 'python programming'

# एक ही key के कई मानों को संभालना
qs = 'tag=python&tag=web&tag=api'
result = parse_qs(qs)
print(result)
# Output: {'tag': ['python', 'web', 'api']}

# parse_qsl, tuples की सूची लौटाता है
result = parse_qsl(qs)
print(result)
# Output: [('tag', 'python'), ('tag', 'web'), ('tag', 'api')]

# रिक्त मानों को बनाए रखें (डिफ़ॉल्ट रूप से इन्हें छोड़ दिया जाता है)
qs = 'name=John&email=&age=30'
print(parse_qs(qs, keep_blank_values=True))
# Output: {'name': ['John'], 'email': [''], 'age': ['30']}

urlparse के साथ पूरे URLs की Encoding

पूर्ण URLs के साथ काम करते समय, Python के urlparse() और urlunparse() फ़ंक्शन आपको URLs को सुरक्षित रूप से विघटित और पुनर्निर्मित करने देते हैं। यह विशेष रूप से तब उपयोगी है जब आपको किसी URL की संरचना को तोड़े बिना उसके विशिष्ट हिस्सों को संशोधित करना हो।

from urllib.parse import urlparse, urlunparse, urlencode, quote

# एक URL को घटकों में parse करें
url = 'https://example.com/search?q=hello&page=1#results'
parsed = urlparse(url)
print(parsed.scheme)    # 'https'
print(parsed.netloc)    # 'example.com'
print(parsed.path)      # '/search'
print(parsed.query)     # 'q=hello&page=1'
print(parsed.fragment)  # 'results'

# घटकों से एक URL बनाएँ
from urllib.parse import ParseResult
new_url = urlunparse(ParseResult(
    scheme='https',
    netloc='api.example.com',
    path='/v2/search',
    params='',
    query=urlencode({'q': 'python & java', 'limit': 10}),
    fragment=''
))
print(new_url)
# Output: https://api.example.com/v2/search?q=python+%26+java&limit=10

# विशेष अक्षरों वाले path segment को सुरक्षित रूप से जोड़ें
base = 'https://example.com/files/'
filename = 'my report (final).pdf'
safe_url = base + quote(filename, safe='')
print(safe_url)
# Output: https://example.com/files/my%20report%20%28final%29.pdf

आधुनिक Python कोड के लिए, requests लाइब्रेरी का उपयोग करने पर विचार करें, जो जब आप parameters को dictionary के रूप में पास करते हैं तो URL encoding को स्वचालित रूप से संभाल लेती है। httpx लाइब्रेरी भी इसी तरह की स्वचालित encoding क्षमताएँ प्रदान करती है।

import requests

# requests, encoding को स्वचालित रूप से संभालता है
response = requests.get(
    'https://api.example.com/search',
    params={
        'q': 'python & java',
        'page': 1,
        'sort': 'relevance'
    }
)
print(response.url)
# https://api.example.com/search?q=python+%26+java&page=1&sort=relevance

संबंधित लेख

हमारे मुफ़्त टूल आज़माएँ