使用python实现一段代码,能够完整保存网页内容、图片、音频文件到指定目录,保存的网页内容可在本地浏览器打开直接还原页面的动态效果
时间: 2024-03-08 15:45:36 浏览: 129
可以使用Python的requests和beautifulsoup库实现保存网页内容、图片和音频文件。以下是一个简单的示例代码:
```python
import requests
from bs4 import BeautifulSoup
import os
# 将保存的目录设置为当前目录下的demo文件夹
SAVE_DIR = os.path.join(os.getcwd(), 'demo')
# 创建保存目录
if not os.path.exists(SAVE_DIR):
os.makedirs(SAVE_DIR)
# 访问网页
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
# 保存网页
html_filename = os.path.join(SAVE_DIR, 'index.html')
with open(html_filename, 'wb') as f:
f.write(response.content)
# 保存图片
img_tags = soup.find_all('img')
for img in img_tags:
img_url = img.get('src')
response = requests.get(img_url)
img_filename = os.path.join(SAVE_DIR, img_url.split('/')[-1])
with open(img_filename, 'wb') as f:
f.write(response.content)
# 保存音频文件
audio_tags = soup.find_all('audio')
for audio in audio_tags:
audio_url = audio.get('src')
response = requests.get(audio_url)
audio_filename = os.path.join(SAVE_DIR, audio_url.split('/')[-1])
with open(audio_filename, 'wb') as f:
f.write(response.content)
```
这段代码会将指定网页的内容、图片和音频文件保存在指定目录下。保存的网页内容可以在本地浏览器打开直接还原页面的动态效果。
阅读全文
相关推荐


















