Python3.6+requests 爬取网站遇到中文乱码怎么办?作者:微软亚洲研究院

您所在的位置:网站首页 2022年博士生考试时间 Python3.6+requests 爬取网站遇到中文乱码怎么办?作者:微软亚洲研究院

Python3.6+requests 爬取网站遇到中文乱码怎么办?作者:微软亚洲研究院

2024-02-12 20:15| 来源: 网络整理| 查看: 265

# -*- 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) 微软äºæ´²ç ç©¶é¢ 茅娄聳茅隆碌 ä½èï¼å¾®è½¯äºæ´²ç ç©¶é¢

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

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

原理:

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

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

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3