python爬取图片保存到本地的源代码
时间: 2023-11-03 21:58:27 浏览: 55
以下是一个简单的Python程序,用于爬取网站上的图片并将其保存到本地:
```python
import requests
import os
url = 'https://www.example.com/images/'
save_path = 'images/'
response = requests.get(url)
content = response.content.decode('utf-8')
lines = content.split('\n')
if not os.path.exists(save_path):
os.makedirs(save_path)
for line in lines:
if '.jpg' in line or '.png' in line:
filename = line.split('/')[-1]
filepath = os.path.join(save_path, filename)
try:
img_response = requests.get(line)
with open(filepath, 'wb') as f:
f.write(img_response.content)
except:
pass
```
在这个例子中,我们首先使用requests库获取网站的内容。然后,我们将内容分割成行,并查找包含.jpg或.png扩展名的行。对于每个包含图片的行,我们从URL中提取文件名,并使用os库将文件保存到指定的路径。