编程语言
首页 > 编程语言> > Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)

Python3的urllib.parse常用函数小结(urlencode,quote,quote_plus,unquote,unquote_plus等)

作者:互联网

本文实例讲述了Python3的urllib.parse常用函数。分享给大家供大家参考,具体如下:

1、获取url参数

>>> 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'
#注意:加号会被解码,可能有时并不是我们想要的
>>> 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')  #未编码斜线
'a%26b/c'
>>> parse.quote_plus('a&b/c')  #编码了斜线
'a%26b%2Fc'

4、unquote/unquote_plus

from urllib import parse
>>> parse.unquote('1+2')  #不解码加号
'1+2'
>>> parse.unquote('1+2')  #把加号解码为空格
'1 2'

转自 https://www.jb51.net/article/92818.htm

标签:unquote,quote,urllib,parse,plus,query
来源: https://www.cnblogs.com/hanfe1/p/14174265.html