python3的UnicodeDecodeError解决方法

yipeiwu_com5年前Python基础

爬虫部分解码异常

response.content.decode() # 默认使用 utf-8 出现解码异常

以下是设计的通用解码

通过 text 获取编码

# 通过 text 获取编码
import requests
from lxml import etree


def public_decode():
 headers = {
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
 }
 response = requests.get('https://blog.csdn.net/a13951206104', headers=headers)
 html = etree.HTML(response.text) # response.text 能自动获取编码, 大多乱码
 _charset = html.xpath('//@charset') or []
 if _charset:
  encode_content = response.content.decode(_charset[0].strip().lower(),
             errors='replace') # 如果设置为replace,则会用?取代非法字符;
  return {'response_text': encode_content, "response_obj": response}
 for _charset_ in ['utf-8', 'gbk', 'gb2312'] # 国内主要这3种:
  if '�' not in response.content.decode(_charset_, errors='replace'):
   return {'response_text': response.content.decode(_charset_, errors='replace'),
     "response_obj": response}
  else:
   # 默认还得是 utf-8
   return {'response_text': response.content.decode('utf-8', errors='replace'),
     "response_obj": response}

通过数据 来解编码(推荐)

def public_decode(response):
 headers = {
  'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
 }
 response = requests.get('https://blog.csdn.net/a13951206104', headers=headers)
 html = etree.HTML(response.text)
 # 不希望抓下来的数据中有非法字符
 item = dict()
 result = None
 for _charset_ in ['utf-8', 'gbk', 'gb2312']:
  if response:
   result = response.content.decode(_charset_, errors='replace')
   item['content'] = html.xpath('//*[@id="content"]')
   if '�' not in result['content'].strip():
    result =response.content.decode(_charset_, errors='replace')
    break
 if not result:
  # 默认 utf-8
  result = response.content.decode(_charset_, errors='replace')
 

errors=‘replace' 使解码不报异常, 然后把几个常用的编码一个个试下, 最后要看落下来的数据, 所以最好拿数据 去获取合适的编码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python协程的用法和例子详解

Python协程的用法和例子详解

从句法上看,协程与生成器类似,都是定义体中包含 yield 关键字的函数。可是,在协程中, yield 通常出现在表达式的右边(例如, datum = yield),可以产出值,也可以不...

Python 记录日志的灵活性和可配置性介绍

Python 记录日志的灵活性和可配置性介绍

对一名开发者来说最糟糕的情况,莫过于要弄清楚一个不熟悉的应用为何不工作。有时候,你甚至不知道系统运行,是否跟原始设计一致。 在线运行的应用就是黑盒子,需要被跟踪监控。最简单也最重要的方式...

Python逐行读取文件中内容的简单方法

Python逐行读取文件中内容的简单方法

项目开发中文件的读写是必不可少的 下面来简单介绍一下文件的读 读文件,首先我们要有文件 那我首先自己创建了一个文本文件password.txt 内容如下: 下面先贴上代码,然后对其进...

windows下ipython的安装与使用详解

windows下ipython的安装与使用详解

ipython的安装 ipython可以直接使用pip install ipython安装 ,如果安装失败按如下步骤手动进行安装 所需文件下载:    ...

python保存文件方法小结

1>保存为二进制文件,pkl格式 import pickle pickle.dump(data,open('file_path','wb')) #后缀.pkl可加可不加 若文...