【问题标题】:persistant non-utf-8 characters in scraped file废料文件中的持久非 utf-8 字符
【发布时间】:2019-12-09 18:49:46
【问题描述】:

我目前正在学习网页抓取,我正在尝试保存页面的 html 版本: "https://www.wuxiaworld.co/Master-Hunter-K/1061716.html" 使用美丽的汤和请求模块。

每次我在 html 文件的统计信息中得到这些  字符时,用 …†而不是 "

这是我的代码:

from bs4 import BeautifulSoup
import requests
link = "https://www.wuxiaworld.co/Master-Hunter-K/1061716.html"
html = requests.get(link,timeout = 2)
soup = BeautifulSoup(html.text,'html.parser')
with open("test.html","a",encoding ="utf-8-sig") as file:
    file.write(str(soup))

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: html python-3.x web-scraping


    【解决方案1】:

    嗯,那叫HTML BOM 代表Byte Order Mark BOM Meaning

    让我们看看这里到底发生了什么:

    import requests
    
    r = requests.get(
        'https://www.wuxiaworld.co/Master-Hunter-K/1061716.html')
    
    print(r.headers['Content-Type'])
    

    文本/html

    那么让我们检查一下编码吧!

    print(r.encoding)
    

    ISO-8859-1

    这是HTML4 的默认值,但HTML5 将是UTF-8

    所以现在我们需要使用请求使其成为apparent

    所以我们将使用

    r.encoding = r.apparent_encoding
    print(r.encoding)
    

    UTF-8-SIG

    最终代码如下:

    import requests
    
    
    r = requests.get(
        'https://www.wuxiaworld.co/Master-Hunter-K/1061716.html')
    r.encoding = r.apparent_encoding
    with open('page.html', 'w', encoding='UTF-8-SIG') as pop:
        pop.write(r.text)
    

    【讨论】:

    • 请在代码中添加解释,以便理解如何解决问题。
    • @ArunVinoth 你有它,所以你可以理解
    • 感谢艾哈迈德先生,过去 2 晚我一直在寻找解决方案,您帮助解决了问题。
    猜你喜欢
    • 2016-05-20
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多