如何在Python 3中进行URL编码?

问题描述:

我曾试图按照the documentation但未能在Python 3使用urlparse.parse.quote_plus()如何在Python 3中进行URL编码?

from urllib.parse import urlparse 

params = urlparse.parse.quote_plus({'username': 'administrator', 'password': 'xyz'}) 

我得到

AttributeError: 'function' object has no attribute 'parse'

你误读的文档。你需要做两件事情:

  1. 报价从你的字典中的每个键和值,和
  2. 编码这些成URL

幸运的是urllib.parse.urlencode确实在一步都那些东西,那就是你应该使用的功能。

from urllib.parse import urlencode, quote_plus 

payload = {'username':'administrator', 'password':'xyz'} 
result = urlencode(payload, quote_via=quote_plus) 
# 'password=xyz&username=administrator'