生成一个python 脚本,内容包含迭代爬取图片,视频,音乐。并包含错误返回信息
时间: 2023-03-13 22:30:35 浏览: 115
利用python进行图片爬取
# 示例代码:
import requests
import urllib.request# 定义函数,用于爬取图片、视频、音乐
def crawl_media(url):
try:
response = requests.get(url)
# 判断文件类型,然后进行相应的处理
if response.headers['Content-Type'].startswith('image'):
# 处理图片
file_name = url.split('/')[-1]
with open(file_name, 'wb') as f:
f.write(response.content)
elif response.headers['Content-Type'].startswith('video'):
# 处理视频
file_name = url.split('/')[-1]
with open(file_name, 'wb') as f:
f.write(response.content)
elif response.headers['Content-Type'].startswith('audio'):
# 处理音乐
file_name = url.split('/')[-1]
with open(file_name, 'wb') as f:
f.write(response.content)
except:
# 请求失败时,打印错误信息
print("爬取失败!")# 迭代爬取所有图片、视频、音乐
urls = ["https://example.com/images/1.jpg", "https://example.com/videos/2.mp4", "https://example.com/audios/3.mp3"]
for url in urls:
crawl_media(url)
阅读全文