【问题标题】:How do I Copy the HTML code of a website to a text file in python?如何将网站的 HTML 代码复制到 python 中的文本文件?
【发布时间】:2021-02-08 20:40:53
【问题描述】:

我试过这个,但我得到这个错误:'UnicodeEncodeError:'charmap'编解码器无法编码位置 286381-286385 中的字符:字符映射到' 导入请求 从 bs4 导入 BeautifulSoup

def main():
    f = open("sites.text", 'w')
    page = requests.get("https://stackoverflow.com")
    soup = BeautifulSoup(page.content, "html.parser")
    f.write(str(soup))
    f.close()

if __name__ == '__main__':
    main()

【问题讨论】:

  • 尝试使用open("sites.text", 'w', encoding='utf8')
  • 不起作用,给我这个错误:LookupError: unknown encoding: uft8

标签: python html file beautifulsoup


【解决方案1】:

试试这个:

with open("example", "w", encoding="utf8") as f:
    page = requests.get("https://www.google.com/").text
    soup = BeautifulSoup(page, "lxml")
    f.write(str(soup))

您需要编码(也可以使用 soup.encode("utf-8"))并使用响应对象的 text 属性。
response.text 以 unicode 形式返回响应的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    相关资源
    最近更新 更多