Python3 urllib.parse common functions summary of urlencode quote quote_plus unquote unquote_plus and so on

  • 2020-05-12 02:49:25
  • OfStack

This article illustrates the urllib.parse common functions of Python3 by example. I will share it with you for your reference as follows:

1. Get url parameter


>>> from urllib import parse
>>> url = r'https://docs.python.org/3.5/search.html?q=parse&check_keywords=yes&area=default'
>>> parseResult = parse.urlparse(url)
>>> parseResult
ParseResult(scheme='https', netloc='docs.python.org', path='/3.5/search.html', params='', query='q=parse&check_keywords=yes&area=default', fragment='')
>>> param_dict = parse.parse_qs(parseResult.query)
>>> param_dict
{'q': ['parse'], 'check_keywords': ['yes'], 'area': ['default']}
>>> q = param_dict['q'][0]
>>> q
'parse'
# Note: the plus sign will be decoded and may not always be what we want 
>>> parse.parse_qs('proxy=183.222.102.178:8080&task=XXXXX|5-3+2')
{'proxy': ['183.222.102.178:8080'], 'task': ['XXXXX|5-3 2']}

2, urlencode


>>> from urllib import parse
>>> query = {
  'name': 'walker',
  'age': 99,
  }
>>> parse.urlencode(query)
'name=walker&age=99'

3, quote/quote_plus


>>> from urllib import parse
>>> parse.quote('a&b/c')  # Uncoded slash 
'a%26b/c'
>>> parse.quote_plus('a&b/c')  # I've coded the slash 
'a%26b%2Fc'

4, unquote/unquote_plus


from urllib import parse
>>> parse.unquote('1+2')  # The plus sign is not decoded 
'1+2'
>>> parse.unquote('1+2')  # Decode the plus sign into a space 
'1 2'

If you still want to ask why there is no urldecode - see example 1 again 5 times. ^_^

More about Python related topics: interested readers to view this site "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article has been helpful to you in Python programming.


Related articles: