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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40557606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:40:05  来源:igfitidea点击:

How to URL encode in Python 3?

pythonurlencode

提问by amphibient

I have tried to follow the documentationbut was not able to use urlparse.parse.quote_plus()in Python 3:

我试图按照文档进行操作,但无法urlparse.parse.quote_plus()Python 3以下内容中使用:

from urllib.parse import urlparse

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

I get

我得到

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

AttributeError: 'function' 对象没有属性 'parse'

回答by Adam Smith

You misread the documentation. You need to do two things:

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

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL
  1. 引用字典中的每个键和值,以及
  2. 将它们编码为 URL

Luckily urllib.parse.urlencodedoes both those things in a single step, and that's the function you should be using.

幸运的是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'

回答by Rich Rajah

For Python 3 you could try using quoteinstead of quote_plus:

对于 Python 3,您可以尝试使用quote代替quote_plus

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

结果:

http%3A%2F%2Fwww.sample.com%2F

Or:

或者:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

结果:

'https://www.sample.com/?id=123%20abc'

回答by rumpel

You're looking for urllib.parse.urlencode

您正在寻找 urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'