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中的global关键字的使用方法

摘要 global 标志实际上是为了提示 python 解释器,表明被其修饰的变量是全局变量。这样解释器就可以从当前空间 (current scope) 中读写相应变量...

python通过socket查询whois的方法

本文实例讲述了python通过socket查询whois的方法。分享给大家供大家参考。具体实现方法如下: import socket s = socket.socket(socket...

简单理解Python中的装饰器

Python的装饰器可以实现在代码运行期间修改函数的上下文, 即可以定义函数在执行之前进行何种操作和函数执行后进行何种操作, 而函数本身并没有任何的改变。 首先, 我们先定义一个函数,...

Python实现微信自动好友验证,自动回复,发送群聊链接方法

Python实现微信自动好友验证,自动回复,发送群聊链接方法

引言: 一开始二维码加群,但是呢,这个东西隔一段时间会过期,我需要 每隔一段时间去更新二维码,然后当群人数超过100人了,只能邀请进群, 这个时候就需要别人添加我为好友,然后我通过,打开...

Python中使用双下划线防止类属性被覆盖问题

Python中使用双下划线防止类属性被覆盖问题

在使用Python编写面向对象的代码时,我们会常常使用“继承”这种开发方式。例如下面这一段代码: class Info: def __init__(self): pass...