为什么会有ISO-8859-1这样的字符集编码

requests会从服务器返回的响应头的 Content-Type 去获取字符集编码,如果content-type有charset字段那么requests才能正确识别编码,否则就使用默认的 ISO-8859-1. 一般那些不规范的页面往往有这样的问题.

\requests\utils.py

def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict. :param headers: dictionary to extract encoding from.
:rtype: str
""" content_type = headers.get('content-type') if not content_type:
return None content_type, params = cgi.parse_header(content_type) if 'charset' in params:
return params['charset'].strip("'\"") if 'text' in content_type:
return 'ISO-8859-1'

如何获取正确的编码

requests的返回结果对象里有个apparent_encoding函数, apparent_encoding通过调用chardet.detect()来识别文本编码. 但是需要注意的是,这有些消耗计算资源.

\requests\models.py

    @property
def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library."""
return chardet.detect(self.content)['encoding']
 

requests的text() 跟 content() 有什么区别?

requests在获取网络资源后,我们可以通过两种模式查看内容。 一个是r.text,另一个是r.content,那他们之间有什么区别呢?

分析requests的源代码发现,r.text返回的是处理过的Unicode型的数据,而使用r.content返回的是bytes型的原始数据。也就是说,r.content相对于r.text来说节省了计算资源,r.content是把内容bytes返回. 而r.text是decode成Unicode. 如果headers没有charset字符集的化,text()会调用chardet来计算字符集,这又是消耗cpu的事情.

通过看requests代码来分析text() content()的区别.

# r.text
@property
def text(self):
"""Content of the response, in unicode. If Response.encoding is None, encoding will be guessed using
``chardet``. The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
""" # Try charset from content-type
content = None
encoding = self.encoding if not self.content:
return str('') # Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding # Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace') return content
# Content
@property
def content(self):
"""Content of the response, in bytes.""" if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed') if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes() self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content
 

requests中文乱码解决方法

方法一: 直接encode成utf-8格式.

r.content.decode(r.encoding).encode('utf-8')
r.encoding = 'utf-8'

方法二:如果headers头部没有charset,那么就从html的meta中抽取.

Python学习--- requests库中文编码问题的更多相关文章

  1. [python 学习] requests 库的使用

    1.get请求 # -*- coding: utf-8 -*- import requests URL_IP = "http://b.com/index.php" pyload = ...

  2. 关于requests库中文编码问题

    转自:代码分析Python requests库中文编码问题 Python reqeusts在作为代理爬虫节点抓取不同字符集网站时遇到的一些问题总结. 简单说就是中文乱码的问题.   如果单纯的抓取微博 ...

  3. 【转】使用Python的Requests库进行web接口测试

    原文地址:使用Python的Requests库进行web接口测试 1.Requests简介 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写, ...

  4. Python爬虫—requests库get和post方法使用

    目录 Python爬虫-requests库get和post方法使用 1. 安装requests库 2.requests.get()方法使用 3.requests.post()方法使用-构造formda ...

  5. python中requests库使用方法详解

    目录 python中requests库使用方法详解 官方文档 什么是Requests 安装Requests库 基本的GET请求 带参数的GET请求 解析json 添加headers 基本POST请求 ...

  6. 解决python的requests库在使用过代理后出现拒绝连接的问题

    在使用过代理后,调用python的requests库出现拒绝连接的异常 问题 在windows10环境下,在使用代理(VPN)后.如果在python中调用requests库来地址访问时,有时会出现这样 ...

  7. python 之Requests库学习笔记

    1.    Requests库安装 Windows平台安装说明: 直接以管理员身份打开cmd运行界面,使用pip管理工具进行requests库的安装. 具体安装命令如下: >pip instal ...

  8. 一起学爬虫——通过爬取豆瓣电影top250学习requests库的使用

    学习一门技术最快的方式是做项目,在做项目的过程中对相关的技术查漏补缺. 本文通过爬取豆瓣top250电影学习python requests的使用. 1.准备工作 在pycharm中安装request库 ...

  9. python的Requests库的使用

    Requests模块: Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更加方便,可以节约我们大量 ...

随机推荐

  1. Spring整合Mybatis原理简单分析

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" ...

  2. 了解Spring-boot-starter常用依赖模块

    Spring-boot的优点: 1.Spring框架的“约定优先于配置(COC)”理念以及最佳实践. 2.针对日常企业应用研发各种场景的Spring-boot-starter自动配置依赖模块,且“开箱 ...

  3. Tomcat学习总结(8)——Tomcat+Nginx集群解决均衡负载及生产环境热部署

    近日,为解决生产环境热部署问题,决定在服务器中增加一个tomcat组成集群,利用集群解决热部署问题. 这样既能解决高并发瓶颈问题,又能解决热部署(不影响用户使用的情况下平滑更新生产服务器)问题. 因为 ...

  4. Docker轻量级web图形页面管理 - Portainer部署记录

    Docker图形页面管理工具基本常用的有三种: Docker UI,Shipyard,Portainer,之前分别介绍了Docker UI和Shipyard部署,下面简单介绍下Portainer部署. ...

  5. SQL Server 笔记

    第一章数据库的基本操作: >创建数据库: create database my_db(逻辑名称) on primary ( name='my_db.mdf',(物理名称) filename='F ...

  6. 异步消息队列Celery

    Celery是异步消息队列, 可以在很多场景下进行灵活的应用.消息中包含了执行任务所需的的参数,用于启动任务执行, suoy所以消息队列也可以称作 在web应用开发中, 用户触发的某些事件需要较长事件 ...

  7. Mouse点击之后,复制GridView控件的数据行

    本篇是实现用mouse点击GridView控件任意一行,把所点击的数据复制至另一个GridView控件上. 实现大概思路,把所点击的数据行的记录主键找出来,再去过滤数据源. 点击功能,已经实现,可以参 ...

  8. 【游记】CCHO TY国初划水记

    没想到第一篇游记竟然是化学国初(其实是上次SXACM时候懒得写 DAY0 一下午做了5个小时的校车,服务区水真贵 肝了4个小时模拟题,颠到崩溃. 下榻在距离山大附不远的一个酒店,高三人好多哇,我们年级 ...

  9. 老男孩教育python全栈第九期视频

    失效了在下面评论即可,会及时更新.python9期已全部更新完 链接: https://pan.baidu.com/s/1VV8_ZyVasK05iKd7QMxO-A 密码: 9zau

  10. gulp前端自动化环境搭建详解

    1.安装 nodejs Grunt和所有grunt插件都是基于nodejs来运行的, https://nodejs.org/ 安装完成之后在终端 node -v 查看安装版本  npm -v 查看np ...