鱼C论坛

 找回密码
 立即注册
查看: 1764|回复: 4

[已解决]求助UnicodeEncodeError

[复制链接]
发表于 2023-3-16 20:57:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
import requests

res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')

print(res.text)
print(res.status_code)
res.encoding = 'uniqude'

file = open('book.html', 'a+')

file.write(res.text)

file.close()

出现
Traceback (most recent call last):
  File "F:/python_s/demo2_1.py", line 14, in <module>
    file.write(res.text)
UnicodeEncodeError: 'gbk' codec can't encode character '\xa9' in position 3738: illegal multibyte sequence错误,这个如何解决呢
最佳答案
2023-3-16 21:00:10
  1. import requests

  2. res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')

  3. print(res.text)
  4. print(res.status_code)
  5. res.encoding = 'utf-8'

  6. file = open('book.html', 'a+', encoding='utf-8')

  7. file.write(res.text)

  8. file.close()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-3-16 21:00:10 | 显示全部楼层    本楼为最佳答案   
  1. import requests

  2. res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')

  3. print(res.text)
  4. print(res.status_code)
  5. res.encoding = 'utf-8'

  6. file = open('book.html', 'a+', encoding='utf-8')

  7. file.write(res.text)

  8. file.close()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-3-16 21:20:14 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-3-16 21:25:38 | 显示全部楼层

  1. import requests
  2. import cchardet

  3. res = requests.get('https://localprod.pandateacher.com/python-manuscript/crawler-html/spider-men5.0.html')

  4. # 判断编码
  5. content = res.content
  6. enc = cchardet.detect(content)
  7. enc = enc['encoding']
  8. print(enc)

  9. # 以指定编码写入
  10. file = open('book.html', 'a+', encoding=enc)

  11. file.write(res.text) # res.text

  12. file.close()
复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-3-16 22:02:30 | 显示全部楼层
这是编码问题。open默认以gbk编码,而网页一般是utf-8
在open函数里加上encoding='utf-8'就可以了

哦对了你的代码因为没来得及关文件
所以如果还报错请重启电脑,把原来的文件删掉
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 12:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表