都在推荐用Requests库,而不是Urllib,但是读取网页的时候中文会出现乱码。

分析:
r = requests.get(“http://www.baidu.com“)
**r.text返回的是Unicode型的数据。
使用r.content返回的是bytes型的数据。
也就是说,如果你想取文本,可以通过r.text。
如果想取图片,文件,则可以通过r.content。**

获取一个网页的内容

方法1:使用r.content,得到的是bytes型,再转为str

url='http://music.baidu.com'
r = requests.get(url)
html=r.content
html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
print(html_doc)

方法2:使用r.text
Requests 会自动解码来自服务器的内容。大多数 unicode 字符集都能被无缝地解码。请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 r.text 之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它.
但是Requests库的自身编码为: r.encoding = ‘ISO-8859-1’
可以 r.encoding 修改编码

url='http://music.baidu.com'
r=requests.get(url)
r.encoding='utf-8'
print(r.text)

获取一个网页的内容后存储到本地

方法1:r.content为bytes型,则open时需要open(filename,”wb”)

r=requests.get("music.baidu.com")
html=r.content
with open('test5.html','wb') as f:
f.write(html)

方法2:r.content为bytes型,转为str后存储

r = requests.get("http://www.baidu.com")
html=r.content
html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
# print(html_doc)
with open('test5.html','w',encoding="utf-8") as f:
f.write(html_doc)

方法3:r.text为str,可以直接存储

r=requests.get("http://www.baidu.com")
r.encoding='utf-8'
html=r.text
with open('test6.html','w',encoding="utf-8") as f:
f.write(html)

Requests+lxml

# -*-coding:utf8-*-
import requests
from lxml import etree url="http://music.baidu.com"
r=requests.get(url)
r.encoding="utf-8"
html=r.text
# print(html)
selector = etree.HTML(html)
title=selector.xpath('//title/text()')
print (title[])

结果为:百度音乐-听到极致

终极解决方法

以上的方法虽然不会出现乱码,但是保存下来的网页,图片不显示,只显示文本。而且打开速度慢,找到了一篇博客,提出了一个终极方法,非常棒。

来自博客

# -*-coding:utf8-*-

import requests

req = requests.get("http://news.sina.com.cn/")

if req.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(req.text)
if encodings:
encoding = encodings[]
else:
encoding = req.apparent_encoding # encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace')
global encode_content
encode_content = req.content.decode(encoding, 'replace') #如果设置为replace,则会用?取代非法字符; print(encode_content) with open('test.html','w',encoding='utf-8') as f:
f.write(encode_content)

winH*posi){
articleBox.css({
'height':winH*posi+'px',
'overflow':'hidden'
})
btnReadmore.click(function(){
articleBox.removeAttr("style");
$(this).parent().remove();
})
}else{
btnReadmore.parent().remove();
}
}
var btnReadmore = $("#btn-readmore");
if(btnReadmore.length>0){
if(currentUserName){
setArticleH(btnReadmore,3);
}else{
setArticleH(btnReadmore,1.2);
}
}
})()
// ]]>

Requests text乱码的更多相关文章

  1. sublime text 乱码生成.dump问题的解决方法

    title: sublime text 乱码生成.dump问题的解决方法 tags: sublime text,sublime text 3,.dump,乱码 grammar_cjkRuby: tru ...

  2. Requests中文乱码解决方案

    分析: r = requests.get(“http://www.baidu.com“) **r.text返回的是Unicode型的数据. 使用r.content返回的是bytes型的数据. 也就是说 ...

  3. Sublime Text 乱码解决(Package Control 和 ConvertToUTF8插件安装)

    Sublime Text的界面正如她的名字sublime一样,充满极客感觉的高大上,而且拥有强大的功能.但是她默认是不支持GBK编码的. 本来安装一个Package Control插件管理,再安装其他 ...

  4. 解决Sublime Text乱码问题

    第一步:安装Package Control 大家如果是在官网下载的Sublime Text 3,那么首先需要安装一个 Package Control包,这是一个用来安装其他插件的包,不管装什么插件,首 ...

  5. requests 中文乱码

    jsUrl = 'http://www.heze.cn/qiye/index.php?a=userinfo&username={}'.format(bizQiyeId)r = requests ...

  6. 记一次requests请求乱码的问题

    太懒了,直接说原因吧: 请求返回的内容含有emoji表情 我的解决办法是替换掉emoji字符: 安装库:pip install emoji 替换:emoji.demojize(CONTENT) 注意, ...

  7. 解决Requests中文乱码【有用】,读取htm文件 读取txt文件报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc8 in position 0

    打开这个网址https://blog.csdn.net/chaowanghn/article/details/54889835 python在open读取txt文件时,出现UnicodeDecodeE ...

  8. requests关于Exceeded 30 redirects问题得出的结论

    昨天一个朋友在爬网页时出现的一个问题,以及后续我对这个问题进行了简单的测试. 先说出现的问题的简单描述. 首先是使用urllib请求网页: #urllib.request发起的请求 import ur ...

  9. requests基本应用

    requests基本功能详解 import requests response = requests.get('https://www.baidu.com') print('type属性:',type ...

随机推荐

  1. CGAL的安装与使用

    CGAL CGAL系大名鼎鼎的计算几何算法库,采用C++语言,代码中大量使用模板,相对比较难读.可以支持float, double, CORE的高精度或者gmp等任意精度库. 安装CGAL 在Wind ...

  2. 加速自己的hexo,使用GitHub+Coding实现国内外网站加速

    在配置好hexo之后,我们发现访问网站很慢,但又不是我们使用的主题的问题,那么就是网络环境的影响,即使我们使用了CDN加速,但还是没有我们国内的网站访问起来快速,(听说去美国的服务器要经过太平洋下面的 ...

  3. 《Spring Cloud微服务 入门 实战与进阶》

    很少在周末发文,还是由于昨晚刚收到实体书,还是耐不住性子马上发文了. 一年前,耗时半年多的时间,写出了我的第一本书<Spring Cloud微服务-全栈技术与案例解析>. 时至今日,一年的 ...

  4. php 交换值

    使用异或和第三参数比较 结果比较:(其中之一) 异或:执行时间在 0.035-0.085之间 第三参数:执行时间在 0.035-0.050之间 结论:使用第三参数执行效率更高/更稳定

  5. vue项目里面使用脚手架实现跨域

    今天在做vue项目的时候,项目在本地,接口数据在阿里云,这就造成了跨域,在网上找了好久,网上大部分的方法都是找到config文件夹下面的index进行修改的,可是我找到的Index却和他们描述的不一样 ...

  6. IT兄弟连 HTML5教程 HTML5的基本语法 如何选择开发工具

    如何选择开发工具 有许多可以编辑网页的软件,事实上你不需要用任何专门的软件来建立HTML页面,你所需要的只是一个文本编辑器(或字处理器),如Office Word.记事本.写字板等.制作页面初学者通常 ...

  7. 如何使用re模块进行测试用例的参数化

    import re import os from scripts.handle_mysql import HandleMysql from scripts.handle_config import H ...

  8. 使用configparser模块进行封装,构造配置文件处理器

    from configparser import ConfigParser class HandleConfig: ''' 定义一个配置文件处理类 ''' def __init__(self, fil ...

  9. 通过 SCQA 的框架来讲故事

    SCQA:Situation情景.Complication冲突.Question疑问. Answer回答   SCQA模型是一个"结构化表达"工具,是麦肯锡咨询顾问芭芭拉·明托在& ...

  10. linux的ls命令详解

    概述 Linux ls命令用于显示指定工作目录下之内容(列出目前工作目录所含之文件及子目录). 语法 ls [-alrtAFR] [name...] 参数 -a 显示所有文件及目录 (ls内定将文件名 ...