如何在Python 3中进行URL编码? [英] How to URL encode in Python 3?

查看:303
本文介绍了如何在Python 3中进行URL编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试遵循文档,但无法执行在Python 3中使用urlparse.parse.quote_plus():

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

from urllib.parse import urlparse

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

我知道

AttributeError:函数"对象没有属性解析"

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

推荐答案

您误读了文档.您需要做两件事:

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

  1. 引用字典中的每个键和值,然后
  2. 将它们编码为URL

幸运的是,urllib.parse.urlencode只需一步即可完成所有这些操作,这就是您应该使用的功能.

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

from urllib.parse import urlencode, quote_plus

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

这篇关于如何在Python 3中进行URL编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆