Python中如何将压缩的HTML响应保存到文件并解压缩
发布时间:2023-12-17 15:50:00
使用Python保存压缩的HTML响应并解压缩可以使用标准库中的gzip和shutil模块。
首先,我们需要发送一个GET请求并获取压缩的HTML响应。我们可以使用requests库来实现这个功能。假设我们已经安装了requests库,代码如下:
import requests
# 发送GET请求
response = requests.get('http://example.com')
# 获取压缩的HTML响应内容
compressed_html = response.content
接下来,我们可以将压缩的HTML内容保存到文件中。可以使用Python的open函数以二进制写入模式打开文件,并将压缩的HTML内容写入文件。
with open('compressed_html.gz', 'wb') as f:
f.write(compressed_html)
现在,我们已经将压缩的HTML内容保存到了文件compressed_html.gz中。接下来,我们需要使用gzip模块解压缩文件中的内容。
import gzip
# 解压缩文件
with gzip.open('compressed_html.gz', 'rb') as f:
decompressed_html = f.read()
# 将解压缩内容保存到文件
with open('decompressed_html.html', 'wb') as f:
f.write(decompressed_html)
在以上代码中,我们使用gzip.open函数以二进制读取模式打开压缩的HTML文件,并使用read方法读取解压缩的内容。然后,我们使用open函数以二进制写入模式打开一个新的文件,将解压缩的内容写入该文件中。
现在,我们已经成功将压缩的HTML响应保存到了文件compressed_html.gz并解压缩到了文件decompressed_html.html中。
下面是一个完整的例子,演示了如何将压缩的HTML响应保存到文件并解压缩:
import requests
import gzip
# 发送GET请求
response = requests.get('http://example.com')
# 获取压缩的HTML响应内容
compressed_html = response.content
# 将压缩的HTML内容保存到文件
with open('compressed_html.gz', 'wb') as f:
f.write(compressed_html)
# 解压缩文件
with gzip.open('compressed_html.gz', 'rb') as f:
decompressed_html = f.read()
# 将解压缩内容保存到文件
with open('decompressed_html.html', 'wb') as f:
f.write(decompressed_html)
print("压缩的HTML响应已保存并解压缩到文件中")
运行以上代码后,压缩的HTML响应将保存到compressed_html.gz文件中,并解压缩到decompressed_html.html文件中。
以上是将压缩的HTML响应保存到文件并解压缩的一个例子。你可以根据实际情况进行适当修改和调整。使用gzip和shutil模块的方法可以适用于其他类型的压缩文件,不仅仅限于HTML响应。
