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中函数的基本定义与调用及内置函数详解

前言 函数function是python编程核心内容之一,也是比较重要的一块。首先我们要了解Python函数的基本定义: 函数是什么? 函数是可以实现一些特定功能的小方法或是小程序。...

Django Sitemap 站点地图的实现方法

Django 中自带了 sitemap框架,用来生成 xml 文件 Sitemap(站点地图)是通知搜索引擎页面的地址,页面的重要性,帮助站点得到比较好的收录。 白话文就是:一个写了你...

详解Python的Django框架中Manager方法的使用

在语句Book.objects.all()中,objects是一个特殊的属性,需要通过它查询数据库。 在第5章,我们只是简要地说这是模块的manager 。现在是时候深入了解manage...

利用Python实现kNN算法的代码

邻近算法(k-NearestNeighbor) 是机器学习中的一种分类(classification)算法,也是机器学习中最简单的算法之一了。虽然很简单,但在解决特定问题时却能发挥很好的...

Pipenv一键搭建python虚拟环境的方法

Pipenv一键搭建python虚拟环境的方法

由于python2和python3在部分语法上不兼容, 导致有人打趣道:"Python2和Python3是两门语言" 对于初学者而言, 如果同时安装了python2和python3, 那...