使用爬虫爬取网页经常遇到各种编码问题,因此产生乱码今天折腾了一天,全部总结一遍环境:win10,pycharm,python3.41.首先先来网页编码是utf-8的:以百度首页为例:使用requests库import requests
url="http://www.baidu.com"response = requests.get(url)content = response.textprint(content)结果有代码显示,但是出现乱码
使用urllib库import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')print(response.read())结果有代码显示,但是以二进制返回
接下来介绍encode()和decode()方法encode()用于解码,decode()方法用于编码注:python3默认编码为utf-8例1:text = '中华'print(type(text))print(text.encode('gbk'))#以gbk形式解码,即把utf-8的字符串text转换成gbk编码print(text.encode('utf-8'))#以utf-8形式解码,因为原本是utf-8编码,所以返回二进制print(text.encode('iso-8859-1'))#报错返回结果:<class 'str'>b'\xd6\xd0\xbb\xaa'b'\xe4\xb8\xad\xe5\x8d\x8e'UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-1: ordinal not in range(256)为什么第四个报错?我查寻了一下latin-1是什么?Latin1是ISO-8859-1的别名,有些环境下写作Latin-1。ISO-8859-1编码是单字节编码。Unicode其实是Latin1的扩展。只有一个低字节的Uncode字符其实就是Latin1字符(这里认为unicode是两个字节,事实上因为各种版本不一样,字节数也不一样)所以我的理解是:因为中文至少两个字节,所以不能解码出来
例2:text = '中华'print(type(text)) #<class 'str'>text1 = text.encode('gbk')print(type(text1)) #<class 'bytes'>print(text1) #b'\xd6\xd0\xbb\xaa'text2 = text1.decode('gbk')print(type(text2)) #<class 'str'>print(text2) #中华text3 = text1.decode('utf-8') #报错:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byteprint(text3)
text4= text.encode('utf-8')print(type(text4)) #<class 'bytes'>print(text4) #b'\xe4\xb8\xad\xe5\x8d\x8e'text5 = text4.decode('utf-8')print(type(text5)) #<class 'str'>print(text5) #中华text6 = text4.decode('gbk') #报错:UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 2: illegal multibyte sequenceprint(text6)
为什么text3和text6会报错呢?因为他们解码和编码使用的编码标准不一样。text1是用gbk解码,那么用utf-8编码回去就会报错,text6同理
好,回到百度例子,那么我们要怎么样才能看到我们想要的网页源代码呢?使用requests库import requests
url="http://www.baidu.com"response = requests.get(url)content = response.text.encode('iso-8859-1').decode('utf-8')#把网页源代码解码成Unicode编码,然后用utf-8编码print(content)
使用urllib库import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')print(response.read().decode(utf-8))
2.关于网页源代码是gbk或者gb2312编码的网页:import requestsresponse = requests.get('http://www.dytt8.net/')#print(response.text)html = response.text
print(html)结果返回乱码
import urllib.request#get请求response = urllib.request.urlopen('http://www.baidu.com')print(response.read())结果返回二进制
正确代码:import requestsresponse = requests.get('http://www.dytt8.net/')#print(response.text)html = response.text.encode('iso-8859-1').decode('gbk')
print(html)
import urllib.request#get请求response = urllib.request.urlopen('http://www.dytt8.net/')print(response.read().decode('gbk'))
转载于:https://www.cnblogs.com/lyxuefeng/p/9018370.html
相关资源:JAVA上百实例源码以及开源项目