python3的UnicodeDecodeError解决方法
2019-12-21 07:08
639 查看
爬虫部分解码异常
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 sqlobject(mysql)中文乱码解决方法
- ArcMap中使用Python遇到中文字段名错误的解决方法
- Python转码问题的解决方法
- python中出现SyntaxError: Non-UTF-8 code 解决方法
- crontab 中 python 脚本执行失败的解决方法
- python处理字符串时出现的错误'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)" 解决方法
- python中cx_Oracle模块安装遇到的问题与解决方法
- 在Windows上安装Python+MySQL 的常见问题及解决方法
- python2.4不支持datetime.strptime方法的解决方法。
- Python:通过执行100万次打印来比较C和python的性能,以及用C和python结合来解决性能问题的方法 .
- mac下安装mysql-python包报unable to execute llvm-gcc-4.2: No such file or directory error: command 'llvm-gcc-4.2' failed with exit status 1解决方法
- python解决字典中的值是列表问题的方法
- Python字符串的encode与decode研究心得乱码问题解决方法
- 解决 Python.h:没有那个文件或目录 错误的方法
- Python字符串的encode与decode研究心得乱码问题解决方法
- 在Windows上安装Python+MySQL 的常见问题及解决方法
- Python Email应用的中文乱码问题解决方法
- 自定义安装 Python 后,出现方向键无法用,按下方向键后,终端显示的式相应的字符编码,而不是方向键的功能的解决方法
- python找不到images模块的解决方法