Python之进行URL编码案例讲解
什么是URL编码
URL编码就是将URL中的特殊字符转换成可以被浏览器正常处理的字符串。在URL中,某些字符是有特殊意义的,比如:问号(?)、等号(=)、和号(&)等,这些特殊字符需要被编码之后才能正常使用。
Python中的URL编码方法
Python中的urllib库提供了对URL进行编码和解码的方法,主要包括urllib.parse.quote()和urllib.parse.unquote()方法。
urllib.parse.quote()
urllib.parse.quote()方法用于将字符串进行URL编码。使用方法如下:
import urllib.parse
url = 'http://www.example.com/api?key=中文'
# 对URL进行编码
url_encoded = urllib.parse.quote(url, safe=':/?=&')
print(url_encoded)
输出结果为:
http%3A//www.example.com/api%3Fkey%3D%E4%B8%AD%E6%96%87
其中,safe参数指定了哪些字符不需要被编码,这里我们指定了“:/?=&”不需要被编码。
urllib.parse.unquote()
urllib.parse.unquote()方法用于将URL编码的字符串进行解码。使用方法如下:
import urllib.parse
url = 'http%3A//www.example.com/api%3Fkey%3D%E4%B8%AD%E6%96%87'
# 对URL进行解码
url_decoded = urllib.parse.unquote(url)
print(url_decoded)
输出结果为:
http://www.example.com/api?key=中文
示例说明
示例一:对URL中的中文进行编码
import urllib.parse
url = 'http://www.example.com/api?key=中文'
# 对URL进行编码
url_encoded = urllib.parse.quote(url, safe=':/?=&')
print(url_encoded)
运行结果:
http%3A//www.example.com/api%3Fkey%3D%E4%B8%AD%E6%96%87
示例二:对URL中的特殊字符进行编码
import urllib.parse
url = 'http://www.example.com/api?key=1+1=2'
# 对URL进行编码
url_encoded = urllib.parse.quote(url, safe=':/?=&')
print(url_encoded)
运行结果:
http%3A//www.example.com/api%3Fkey%3D1%2B1%3D2
在这个例子中,我们将“1+1=2”中的加号进行了编码。这样,在浏览器中访问该URL时,浏览器会正确地将“1+1=2”作为参数传递给API。