Python3中GBK编码错误的处理与十六进制存储方案

Alice
Alice
发布时间:2026-10-16 | 5人浏览过
原创

本文介绍Python3中常见的GBK编码错误,提供忽略非法字符的URL处理方案,以及将GBK数据转换为十六进制文本存储再还原的方法,确保数据完整性。

Python3中GBK编码错误的处理与十六进制存储方案

在Python3进行字符串处理时,

经常遇到'gbk' codec can't encode character '\xa0'错误,这通常是因为字符串中包含无法被正确编码的字符。

可以通过以下方法解决该问题。

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完全转换为UTF-8。

对于必须存储的情况,可以将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编码内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表