python3里gbk编码的问题解决 在python3有关字符串的处理当中,经常会遇到 'gbk' codec can't encode character '\xa0'这个问题,原因是在str里面存在着不能正确编码的字符. 通过以下方法即可解决. import requests from bs4 import BeautifulSoup url = http://jecvay.com/2015/03/learni
在python3有关字符串的处理当中,经常会遇到
'gbk' codec can't encode character '\xa0'
这个问题,原因是在str里面存在着不能正确编码的字符。
通过以下方法即可解决。
import requests
from bs4 import BeautifulSoup
url = "http://jecvay.com/2015/03/learning-compilers-1.html"
url = url.encode('gbk','ignore').decode('utf-8') //忽略
response = requests.get(url)
print(response)
soup = BeautifulSoup(response.text)
print(soup.body.text)
以上方法在必须要记录数据的时候会出现数据不准确问题
python3 字符串无法将 gbk 完全转换为utf8
对于必须存储的情况,将gbk -> 十六进制字节码文本 保存,需要的时候在转换为gbk以便显示。
def string_hex(data):
lin = ['%02X' % i for i in data]
return "".join(lin).upper()
def __ToUTF8(tuple):
lists = []
for itme in tuple:
tmp = itme
if type(itme) == bytes:
try:
tmp = itme.decode('gbk')
except UnicodeDecodeError:
tmp = string_hex(itme)
lists.append(tmp)
return lists
def readFileAll(file):
with open(file, 'rb') as f:
data = f.read()
return data
s = readFileAll('gkb.txt') //gbk 字符串文件
sx = string_hex(s)//转化为16进制文本
print(sx)
到此这篇关于python3里gbk编码的问题解决的文章就介绍到这了,更多相关python3 gbk编码内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
本文标题为:python3里gbk编码的问题解决


- python中列表添加元素的几种方式(+、append()、ext 2022-09-02
- Python之路-Python中的线程与进程 2023-09-04
- Python Pandas如何获取和修改任意位置的值(at,iat,loc,iloc) 2023-08-04
- windows安装python2.7.12和pycharm2018教程 2023-09-03
- Python实现将DNA序列存储为tfr文件并读取流程介绍 2022-10-20
- CentOS7 安装 Python3.6 2023-09-04
- 在centos6.4下安装python3.5 2023-09-04
- python中defaultdict用法实例详解 2022-10-20
- Python 保存数据的方法(4种方法) 2023-09-04
- python线程池ThreadPoolExecutor与进程池ProcessPoolExecutor 2023-09-04