一天一bug,个个不一样。
今天在编写python爬虫时,又遇到了乱码。
先看一下我编写的代码:
import requests
from fake_useragent import UserAgent
url = "http://www.farmer.com.cn/2021/01/25/99864972.html"
headers = {
'User-Agent': UserAgent().random
}
response = requests.get(url, headers=headers)
print(response.text)
再看一下乱码的模式:
回头查看网页代码与编译器都是采用utf-8编码。
可为什么还是出现了乱码了呢?
有疑问,上百度。有一篇博文引起了我的注意。
我们通过编写代码查看一下:
import requests
from fake_useragent import UserAgent
import sys
url = "http://www.farmer.com.cn/2021/01/25/99864972.html"
headers = {
'User-Agent': UserAgent().random
}
response = requests.get(url, headers=headers)
print(sys.getdefaultencoding()) # 查看编译器的编码
print(response.encoding) # 查看网页的编码格式
惊奇的发现,网页的编码格式变成了ISO-8859-1
怎么回事?
原来一起原因都是由于网页压缩造成的。
通过查看浏览器响应头:发现了gzip字样。
找到了原因我们就容易解决问题了:
解决方案如下:
import requests
from fake_useragent import UserAgent
url = "http://www.farmer.com.cn/2021/01/25/99864972.html"
headers = {
'User-Agent': UserAgent().random
}
response = requests.get(url, headers=headers)
# encode编码,将ISO-8859-1编码成unicode
# decode解码,将unicode解码成utf-8
print(response.text.encode('ISO-8859-1').decode('UTF-8'))
下面我们来看一下效果: