Python Requests 包中的 URI 编码 [英] URI encoding in Python Requests package

查看:29
本文介绍了Python Requests 包中的 URI 编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python requests 包从 API 获取结果,并且 URL 包含 + 登录.但是当我使用 requests.get 时,请求失败,因为 API 无法理解 + 符号.如果我用 %2B(URI 编码)替换 + 符号,请求就会成功.

有没有办法对这些字符进行编码,以便我在将 URL 传递给请求包时对其进行编码

错误:test user@gmail.com 不存在API:https://example.com/test+user@gmail.com

解决方案

您可以使用 requests.utils.quote(这只是 一个链接urllib.parse.quote) 将您的文本转换为 url 编码格式.

<预><代码>>>>进口请求>>>requests.utils.quote('test+user@gmail.com')'test%2Buser%40gmail.com'

I am using python requests package to get results from a API and the URL contains + sign in it. but when I use requests.get, the request is failing as the API is not able to understand + sign. how ever if I replace + sign with %2B (URI Encoding) the request is successful.

Is there way to encode these characters, so that I encode the URL while passing it to the requests package

Error: test user@gmail.com does not exist
API : https://example.com/test+user@gmail.com

解决方案

You can use requests.utils.quote (which is just a link to urllib.parse.quote) to convert your text to url encoded format.

>>> import requests
>>> requests.utils.quote('test+user@gmail.com')
'test%2Buser%40gmail.com'

这篇关于Python Requests 包中的 URI 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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