python爬取图片代码
时间: 2023-03-25 09:01:24 浏览: 92
以下是一个简单的 Python 爬取图片的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com/images/'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
images = soup.find_all('img')
for img in images:
img_url = img['src']
img_name = img['alt']
img_data = requests.get(img_url).content
with open(img_name, 'wb') as f:
f.write(img_data)
```
这段代码可以爬取指定网站上的所有图片,并将其保存到本地。
相关问题
python爬取批量图片代码
以下是使用Python爬取批量图片的代码:
```python
import requests
import os
# 创建存储图片的文件夹
if not os.path.exists('images'):
os.makedirs('images')
# 爬取图片
url = 'http://example.com/images/'
for i in range(1, 11):
image_url = url + str(i) + '.jpg'
response = requests.get(image_url)
with open('images/' + str(i) + '.jpg', 'wb') as f:
f.write(response.content)
```
以上代码将从`http://example.com/images/1.jpg`到`http://example.com/images/10.jpg`的所有图片保存在`images`文件夹中。你可以根据自己的需要修改代码来适应不同的爬取需求。
python爬虫爬取图片代码
以下是一个简单的 Python 爬虫爬取图片的示例代码:
```python
import requests
import os
url = 'https://www.example.com/image.jpg' # 图片 URL
path = './images' # 存储路径
if not os.path.exists(path):
os.makedirs(path)
response = requests.get(url)
if response.status_code == 200:
with open(path + '/image.jpg', 'wb') as f:
f.write(response.content)
print('图片保存成功!')
else:
print('图片下载失败')
```
以上代码使用 requests 库下载图片并将其保存到指定路径。你可以使用该代码为自己的项目编写图片爬虫。