使用python批量爬取图片并改名字为1,2,3····保存到文件夹中给出具体代码
时间: 2023-12-11 18:02:56 浏览: 48
以下是一个简单的Python代码,可以批量爬取图片并将它们重命名为数字:
```python
import requests
import os
# URL of the image to be downloaded
url = "https://example.com/image.jpg"
# Folder to save the images
folder = "images"
# Create the folder if it does not exist
if not os.path.exists(folder):
os.makedirs(folder)
# Download the image and save it to a file
response = requests.get(url)
with open(os.path.join(folder, "1.jpg"), "wb") as f:
f.write(response.content)
# Repeat the above steps for each image, incrementing the filename number
# Example:
# response = requests.get("https://example.com/image2.jpg")
# with open(os.path.join(folder, "2.jpg"), "wb") as f:
# f.write(response.content)
```
该代码将下载名为 "image.jpg" 的图像,并将其保存到名为 "images" 的文件夹中,使用数字 "1" 作为文件名。您可以使用相同的代码并多次调用 `requests.get()` 和 `open()` 来处理更多的图像,每次递增文件名数字即可。