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最基本的输入输出详解

输出 用print加上字符串,就可以向屏幕上输出指定的文字。比如输出'hello, world',用代码实现如下: >>> print 'hello, world'...

Python2和Python3.6环境解决共存问题

Linux下安装Python3.6和第三方库 /post/150478.htm 如果本机安装了python2,尽量不要管他,使用python3运行python脚本就好,因为可能有程序依...

Python小程序之在图片上加入数字的代码

Python小程序之在图片上加入数字的代码

在GitHub上发现一些很有意思的项目,由于本人作为Python的初学者,编程代码能力相对薄弱,为了加强Python的学习,特此利用前辈们的学习知识成果,自己去亲自实现。 来源:Gi...

python入门之语句(if语句、while语句、for语句)

python入门之语句,包括if语句、while语句、for语句,供python初学者参考。 //if语句例子 name = 'peirong'; if name == 'peir...

Python threading多线程编程实例

Python 的多线程有两种实现方法: 函数,线程类 1.函数 调用 thread 模块中的 start_new_thread() 函数来创建线程,以线程函数的形式告诉线程该做什么 复制...