爬虫爬取的网页 乱码 response.encoding = "utf-8" 来解决

使用requests爬数据的时候,发现打印或者保存到文件中的中文显示为Unicode码(其实我也不知道是什么码,总之乱码)。

爬取某网 response= requests.get(“http://www.xxxxx.com/“)

我们都知道response有 textcontent 这两个property, 它们都是指响应内容,但是又有区别。我们从doc中可以看到:

text的doc内容为:

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.

而content的doc内容为:

Content of the response, in bytes.

其中text是unicode码,content是字节码.

我们看一下网页的 headers,网页源码标签下标签中charset指定的字符编码,例如:

因此,当我们用text属性获取了html内容出现unicode码时,可以通过设置字符编码response.encoding 来匹配指定的编码,这样就不会乱码了。

import requests

response = requests.get(“http://www.xxxxx.com/“)
response.encoding = “utf-8” # 手动指定字符编码为utf-8
print(response.text)

  • 10
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值