将url编码数据转换为简单字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。如若转载,请注明出处! https://blog.csdn.net/Homewm/article/details/84778808

将url编码数据转换为简单字符串

python3中

import urllib
data = open('zgd.txt','r').readlines()
query_list = []
for d in data:
    d = str(urllib.parse.unquote(d))   #converting url encoded data to simple string
    query_list.append(d)
print query_list

python2中

其中在python2中的urllib、urllib2和urlparse中无法找到parse模块,在python2的urlparse库中找到了unquote

from urlparse import unquote
data = open('zgd.txt','r').readlines()
query_list = []
for d in data:
    d = str(unquote(d))   #converting url encoded data to simple string
    query_list.append(d)
print query_list

url编码和解码问题:

urlencode、quote、unquote三个的使用,没有urldecode。

(1)urlencode的参数是词典,而quote处理的是字符串

       它可以将key-value这样的键值对转换成我们想要的格式。如果使用的是python2,urlencode在urllib.urlencode。如果使用的是python3,urlencode在urllib.parse.urlencode。

import urllib.parse
data={"name":"王尼玛","age":"/","addr":"abcdef"}
print(urllib.parse.urlencode(data))
###输出为:addr=abcdef&name=%E7%8E%8B%E5%B0%BC%E7%8E%9B&age=%2F

print(urllib.parse.quote("hahaha你好啊!"))
输出为:hahaha%E4%BD%A0%E5%A5%BD%E5%95%8A%EF%BC%81

(2)urllib存在unquote而没有urldecode

       当urlencode之后的字符串传递过来之后,接受完毕就要解码了。urllib提供了unquote()这个函数,可没有urldecode()!

import  urllib.parse
data={"name":"王尼玛","age":"/","addr":"abcdef"}
print(urllib.parse.urlencode(data))
print(urllib.parse.quote("hahaha你好啊!"))
print(urllib.parse.unquote("hahaha%E4%BD%A0%E5%A5%BD%E5%95%8A%EF%BC%81"))

 更为详细请参考:https://blog.csdn.net/a359680405/article/details/44857359

猜你喜欢

转载自blog.csdn.net/Homewm/article/details/84778808