python中的URL编码 [英] URL encoding in python

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

问题描述

我在 urllib 或其他库中是否有一个简单的方法来完成此任务? URL编码用%后跟两个十六进制数字替换不安全的ASCII字符。

Is there a simple method I'm missing in urllib or other library for this task? URL encoding replaces unsafe ASCII characters with a "%" followed by two hexadecimal digits.

以下是输入和我预期输出的示例:

Here's an example of an input and my expected output:

Mozilla/5.0 (Linux; U; Android 4.0; xx-xx; Galaxy Nexus Build/IFL10C) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

Mozilla%2F5.0+%28Linux%3B+U%3B+Android+4.0%3B+xx-xx%3B+Galaxy+Nexus+Build%2FIFL10C%29+AppleWebKit%2F534.30+%28KHTML%2C+like+Gecko%29+Version%2F4.0+Mobile+Safari%2F534.30


推荐答案

对于Python 2.x,使用 urllib.quote

For Python 2.x, use urllib.quote


使用%xx转义替换字符串中的特殊字符。从不引用字母,数字和字符'_.-'。默认情况下,此函数用于引用URL的路径部分。可选的安全参数指定不应引用的其他字符 - 其默认值为'/'。

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL. The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'.

示例:

In [1]: import urllib

In [2]: urllib.quote('%')
Out[2]: '%25'

编辑

在您的情况下,为了用加号替换空格,您可以使用 urllib.quote_plus

In your case, in order to replace space by plus signs, you may use urllib.quote_plus

示例:

In [4]: urllib.quote_plus('a b')
Out[4]: 'a+b'

对于Python 3.x,使用报价

For Python 3.x, use quote

>>> import urllib
>>> a = "asdas#@das"
>>> urllib.parse.quote(a)
'asdas%23%40das'

and带空格的字符串'quote_plus'

and for string with space use 'quote_plus'

>>> import urllib
>>> a = "as da& s#@das"
>>> urllib.parse.quote_plus(a)
'as+da%26+s%23%40das'

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

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