Python 3 写文件 UnicodeEncodeError: 'gbk' codec can't encode character

发布时间:2022-06-28 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python 3 写文件 UnicodeEncodeError: 'gbk' codec can't encode character脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Python 3 写文件

UnicodeEncodeError: 'gbk' codec can't encode character

 

网页代码中存在“”<meta charset="gbk">“”,如果存为 utf-8,再用浏览器打开,会出现乱码。因此,必须存为 gbk。

 

解决方法:

在写入 string 到文件时,采用   string.encode("gbk", 'ignore').decode("gbk", "ignore")

 

From selenium import webdriver
import time

browser = webdriver.Firefox(executable_path ="D:Softwaregeckodriver-v0.30.0-win64geckodriver.exe")

get_htML = "test2.html"
# 打开文件,准备写入
f = oPEn(get_html, "w", encoding='gbk') ## gbk f = open(get_html, "w", encoding='utf-8')
url = 'https://www.lewen5.COM/Book/45966/'  # 这里填你要保存的网页的网址
browser.get(url)
time.sleep(2)  # 保证浏览器响应成功后再进行下一步操作
# 写入文件
PRint(browser.page_source )  # 忽略非法字符

print(type(browser.page_source) )
#f.wrITe(browser.page_source.encode('GBK',"ignore").decode())  # 忽略非法字符
f.write(browser.page_source.encode("gbk", 'ignore').decode("gbk", "ignore"))  # 忽略非法字符
#f.write(browser.page_source)  # 忽略非法字符
print('写入成功')
# 关闭文件
f.close()

 

脚本宝典总结

以上是脚本宝典为你收集整理的Python 3 写文件 UnicodeEncodeError: 'gbk' codec can't encode character全部内容,希望文章能够帮你解决Python 3 写文件 UnicodeEncodeError: 'gbk' codec can't encode character所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。