Python3.6+requests 爬取网站遇到中文乱码怎么办?ä½œè€…ï¼šå¾®è½¯äºšæ´²ç ”ç©¶é™¢

# -*- coding:utf-8 -*-
import requests
import json
import time
import random
from lxml import etree


url = 'https://www.msra.cn/zh-cn/news/features/bma-20170207'
# 伪装成Mozilla浏览器,解决反爬虫
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
# 生成属性字典
headers = {'User-Agent': user_agent}
# 获取目标网站的HTML页面
response = requests.get(url, headers=headers)
# print(response.text)
a = response.content
selector = etree.HTML(a)
print(selector)
这是结果

Connected to pydev debugger (build 181.4445.76)
<Element html at 0x2492bb71248>
微软äºæ´²ç ç©¶é¢
茅娄聳茅隆碌
ä½èï¼å¾®è½¯äºæ´²ç ç©¶é¢ 

之前使用python2.7遇到许多这样的编码问题,本以为转战3版本就不会遇见了。今天遇到的这个问题,找了挺久资料,终于找到解决方案:

把  response.content  改成  response.text  ,这样问题就解决了。

原理:

resp.text返回的是Unicode型的数据。
resp.content返回的是bytes型也就是二进制的数据

因此如果我们想读取解析文本数据时,使用的是response.text。而想读取解析图片文件,往往使用的就是response.content

猜你喜欢

转载自blog.csdn.net/weixin_41931602/article/details/81181946