要将SEC 10-K年度报告文本保存到文件中,首先需要解决可能遇到的解码问题。以下是一个可能的解决方法的示例代码:
import requests
import os
def save_10k_report(report_url, save_path):
response = requests.get(report_url)
if response.status_code == 200:
content_type = response.headers['Content-Type']
if 'charset' in content_type:
encoding = content_type.split('charset=')[-1]
else:
encoding = 'utf-8'
content = response.content.decode(encoding)
with open(save_path, 'w', encoding=encoding) as file:
file.write(content)
# 示例用法
report_url = 'https://www.sec.gov/Archives/edgar/data/320193/000032019320000010/a10-k20199282020.htm'
save_path = '10k_report.txt'
save_10k_report(report_url, save_path)
在上述示例代码中,我们使用requests
库发送请求获取报告的文本内容。然后,我们检查响应的Content-Type
头信息,获取报告内容的编码方式。如果Content-Type
中包含了charset
信息,我们使用该编码方式进行解码;否则,默认使用UTF-8编码。
最后,我们使用open
函数将文本内容写入到指定的文件中。
请注意,在示例中,我们假设报告的内容是以文本形式返回的。如果报告以其他格式返回(如PDF或其他二进制格式),则需要相应地修改代码来保存正确的内容。