SLASH_W1 2022-01-06 21:51 采纳率: 0%
浏览 47

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

目的是想保存一个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

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

  • 写回答

4条回答 默认 最新

  • CSDN专家-showbo 2022-01-06 22:02
    关注

    改下面就可以了

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

    img


    img

    评论

报告相同问题?

问题事件

  • 创建了问题 1月6日