zoukankan      html  css  js  c++  java
  • 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:\software\geckodriver-v0.30.0-win64\geckodriver.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()
  • 相关阅读:
    HTCVive摄像头的一些好玩的现象
    AI之A*算法
    C#预处理器指令之#define/#undefine/#if/#elif/#else/#endif
    AI之有限状态机
    Unity之动态加载场景资源
    Canvas
    DFGUI之界面文字显示异常
    Unity Application
    AI:确定性AI
    php正则表达式
  • 原文地址:https://www.cnblogs.com/emanlee/p/15643501.html
Copyright © 2011-2022 走看看