python 中文乱码处理分析过程

每个pyhton 页面顶端配置

#-*- coding:utf-8 -*-

提取href中的值

request请求:

house_url =('http://www.fangyuanxinxiwang.com/'+house.xpath('a/@href')[0])

本地页面请求:

for hrefs in td_list[11].find_all('a'):

url_a=hrefs.get('href')

list 类型转化 str :' '.join(list_name) list(str_name)

获取系统编码格式

import sys

print(sys.getfilesystemencoding())

获取get请求响应页面的字符编码格式

htm = requests.get(url, headers=headers)

print('响应:\nencoding={}'.format(htm.encoding))

--用指定的编码格式解析出来,然后再用指定的编码格式进行编码
'str'.decode('utf-8').encode('utf-8') 

--用指定的编码格式解析出来,然后再用指定的编码格式进行编码
'str'.decode('utf-8').encode('utf-8') 

#Python decode() 方法以 encoding 指定的编码格式解码字符串。默认编码为字符串编码。

#Python encode() 方法以 encoding 指定的编码格式编码字符串。errors参数可以指定不同的错误处理方案。

提示错误:AttributeError: ‘str‘ object has no attribute ‘decode‘

原因:

1、Python2和Python3在字符串编码上的区别。

2、Python 3.4: str : AttributeError: ‘str’ object has no attribute 'decode

解决方法:

#必须将字节字符串解码后才能打印出来
print (‘张俊’.encode(‘utf-8’). decode(‘utf-8’) ) 

#<class 'str'> 不进行编码的情况下为string类型 
str='\n'.join(title) print(type(str)) 

#<class 'bytes'> 编码后的类型为bytes
str = str.encode('ISO-8859-1') print(type(str)) 
 
#<class 'str'> 解码后为string类型
str=str.decode('utf-8') print(type(str)) 

总结方法为:获取响应页面的字符编码后,依照其编码格式进行编码,然后再按照编辑工具使用的字符编码进行解码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值