Python Image Downloader: Script Example
Below is a sample code written in Python for scraping images and downloading them to a specified folder.
import requests
import os
def download_image(url, save_dir):
# 发送HTTP GET请求获取图片数据
response = requests.get(url)
# 获取图片名称
image_name = url.split("/")[-1]
# 拼接保存图片的完整路径
save_path = os.path.join(save_dir, image_name)
# 保存图片到指定文件夹
with open(save_path, 'wb') as file:
file.write(response.content)
print(f"图片 {image_name} 下载完成!")
def crawl_images(url, save_dir):
# 发送HTTP GET请求获取网页内容
response = requests.get(url)
# 提取网页中的图片链接
image_urls = re.findall('<img.*?src="(.*?)".*?>', response.text, re.S)
# 逐个下载图片
for image_url in image_urls:
# 判断图片链接是否为完整的URL地址
if image_url.startswith("http"):
download_image(image_url, save_dir)
else:
download_image(url + image_url, save_dir)
# 要爬取的网页地址
url = "http://example.com"
# 要保存图片的文件夹路径
save_dir = "/path/to/save/dir"
# 创建保存图片的文件夹
os.makedirs(save_dir, exist_ok=True)
# 开始爬取图片
crawl_images(url, save_dir)
Replace http://example.com with the webpage address from which you want to crawl images, and replace /path/to/save/dir with the directory path where you want to save the images. After running the code above, the program will crawl images from the specified webpage and save them to the designated folder.