简体   繁体   English

如何将网站的 HTML 代码复制到 python 中的文本文件中?

[英]How do I Copy the HTML code of a website to a text file in python?

I have tried this, but I get this error: 'UnicodeEncodeError: 'charmap' codec can't encode characters in position 286381-286385: character maps to ' import requests from bs4 import BeautifulSoup我试过这个,但我得到这个错误:'UnicodeEncodeError:'charmap'编解码器无法编码 position 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()

Try this:尝试这个:

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

You need to encode (also possible with soup.encode("utf-8")) and use text attribute of response object.您需要编码(也可以使用 soup.encode("utf-8"))并使用响应 object 的文本属性。
response.text returns the content of the response, in unicode. response.text 返回响应的内容,在 unicode 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用python从文本文件中复制特定字符串? - How do I copy specific strings from a text file with python? 如何使用 Python 和 BeautifulSoup 在网站的 HTML 代码中找到特定文本? - How can I find specific text in a website's HTML code with Python and BeautifulSoup? 如何将代码的输出保存到文本文件以进行记录(python) - How do I save the outputs of a code to a text file for logging (python) 如何将描述代码的文本添加到Python源文件中? - How do I add text describing the code into a Python source file? 如何使用selenium Python复制不在html代码中的输入文本 - How to copy the text of an input, which is not in the html code with selenium Python 如何以格式化文本从 html 文件复制到 Python 中的剪贴板? - How can I copy from an html file to the clipboard in Python in formatted text? 如何使用python从某个网站复制文本? - How to copy the text from certain Website with python? 如何从网站中提取文本(html) - How do I extract a text from a website(html) Python Selenium:如何在文本文件中打印来自网站的值? - Python Selenium: How do I print the values from a website in a text file? 我如何使用 jupyter 笔记本的 python 代码从网站下载 csv 文件 - how do i download the csv file from a website using python code for my jupyter notebook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM