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)) 

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

猜你喜欢

转载自blog.csdn.net/weixin_40648849/article/details/124015822