Python学习小记-常用编码知识总结-2020-3-4

昨天学习Python爬虫遇到了很多关于编码的错误,找了一些常用的编码方法
下面进行总结,直接上代码:

#关于编码问题的笔记
import urllib.parse  #导入urllib模块

# 对字符串进行编码
c = "要编码的内容"
s = c.encode("utf8")
print(s)
# 打印结果为:b'\xe8\xa6\x81\xe7\xbc\x96\xe7\xa0\x81\xe7\x9a\x84\xe5\x86\x85\xe5\xae\xb9'
print(s.decode("utf8"))#解码

s = urllib.parse.quote(c) #对字符串变量进行编码
print(s)

dic = {"user":"tom","pwd":"123"}
s = urllib.parse.urlencode(dic,encoding="utf8").encode("utf8")  #对字典进行编码的方法, 编码并且转成unicode
print(s)

post 请求的时候通常要对字典进行编码,其中用到urllib库中的方法
最后还要转换成unicode 。

发布了13 篇原创文章 · 获赞 0 · 访问量 307

猜你喜欢

转载自blog.csdn.net/qq_42788765/article/details/104646642