让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
问题描述
如何使用Python将爬取的内容保存到桌面txt文件中?
解决方案
- 确定保存路径 首先我们需要确定保存路径,这里可以使用os模块获取当前用户的桌面路径: import os desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop') # 获取桌面路径
- 打开文件并写入内容 使用open()函数打开文件,并使用write()函数将爬取的内容写入到文件中: with open(desktop_path + '/test.txt', 'w', encoding='utf-8') as f: f.write('Hello world!') 这里的第一个参数为保存路径,第二个参数为打开模式,'w'表示写入模式;第三个参数为编码方式,utf-8可以保证中文字符不会出现乱码。 完整代码 import requests import os desktop_path = os.path.join(os.path.expanduser("~"), 'Desktop') # 获取桌面路径 url = 'https://www.baidu.com' response = requests.get(url) text = response.text with open(desktop_path + '/test.txt', 'w', encoding='utf-8') as f: f.write(text) 参考文献 Python官方文档:https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files