这是为什么呢?保存网页乱码

目的是想保存一个html文档(中英文都含有的诗词名句网页https://www.shicimingju.com/chaxun/zuozhe/1.html),由于总是出现乱码格式就在发送请求的时候加了一句.encode('iso-8859-1'),保存用的是常规方法write(),结果总运行出错,但是我在爬取同样是含有中英文的淘宝网页https://www.taobao.com/就没有问题,当我去套用爬取淘宝网页的代码时,中文保存还是存在问题
这是淘宝网页正常爬取的代码和结果

import requests
url="https://www.taobao.com/"
response=requests.get(url=url)
page_txt=response.text
#print(page_txt)
with open('taobao','w',encoding='utf-8') as fp:
    fp.write(page_txt)
print('爬取结束')

img

这是最开始的代码

import requests
from bs4 import BeautifulSoup
# 对首页页面进行抓取
headers={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36'
}
url='https://www.shicimingju.com/chaxun/zuozhe/1.html'
page_text=requests.get(url=url,headers=headers).text.encode('iso-8859-1')
soup=BeautifulSoup(page_text,'lxml')
print(soup)
'''
with open('./shici.html','w',encoding='utf-8') as fp:
    fp.write(page_text)
    print('抓取完成!')
'''

到print(soup)没啥问题,输出结果还是正确的格式,但是保存就出错

img

这是套用淘宝的代码

import requests
url="https://www.shicimingju.com/chaxun/zuozhe/1.html"
response=requests.get(url=url)
page_txt=response.text
#print(page_txt)
with open('./sc.html','w',encoding='utf-8') as fp:
    fp.write(page_txt)
print('爬取结束')

虽然运行成功了,但是保存的文件里的中文是乱码

img

应该还是编码格式的问题,但是我不知道怎么解决,还请各位帮忙解答!

改下面就可以了

page_text=requests.get(url=url,headers=headers).content.decode('utf-8')

img


img

你requests 读取页面文件的编码不对 ,用 response.encoding='utf-8'或response.encoding='gbk'设置下读取页面文件用的编码, 再获取res.text即可,比如

response=requests.get(url=url)
response.encoding = 'utf-8'
page_txt=response.text

你这个页面的编码是utf-8 就要设置 response.encoding='utf-8'

import requests
url="https://www.shicimingju.com/chaxun/zuozhe/1.html"
response=requests.get(url=url)
response.encoding = 'utf-8'
page_txt=response.text
print(page_txt)
with open('./sc.html','w',encoding='utf-8') as fp:
    fp.write(page_txt)
print('爬取结束')

或者也可以设置 response.encoding=response.apparent_encoding 自动从网页的内容中分析网页编码

如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

img

charset=utf8的呀 requests请求的时候设置下编码试试吧

楼上都说对了,每个网页的编码不一样,你按照相应编码的转就行