在爬虫时,经常遇到中文乱码,其实在requests获取response时进行转码即可
def crawler():
baseurl="http://www.weather.com.cn/weather/101010100.shtml"
r=requests.get(url=baseurl)
r.encoding="utf-8"
# 感觉直接r.text传入就可以处理乱码问题,上面那句可以不填入
res=r.text
html=etree.HTML(res)
#
data=html.xpath("//li[@class='sky skyid lv4 on'][1]//p[@class='tem']//text()")
print(data)
crawler()
=================================
['\n', '15', '/', '3℃', '\n']
此时爬取到的数据就是中文的了。
unicode转中文
str = ‘\u5927\u77f3\u8857\u9053\u690d\u6751\u4e09\u8def\u56db\u5df79\u53f7’
使用:str.encode(‘utf-8’).decode(‘unicode_escape’)
str.encode('utf-8').decode('unicode_escape')
抓取的HTML中含有 ↵ 符号处理
先使用 json.dumps() 编码,将↵变成\n,然后把\n替换成空白字符
再使用 json.loads() 解码就可以了
import json
a = "HTML ↵"
print(json.loads(json.dumps(a).replace("\n"," ")).strip())
本文介绍了解决爬虫在抓取中文网页时遇到的乱码问题的方法,通过设置requests的编码方式为utf-8来正确解析中文字符,并提供了unicode转换为中文的示例。
5382

被折叠的 条评论
为什么被折叠?



