在网上爬图片的python程序
时间: 2024-04-19 07:23:50 浏览: 9
您好!您可以使用Python中的requests库和BeautifulSoup库来编写一个简单的爬取图片的程序。下面是一个示例代码:
```python
import requests
from bs4 import BeautifulSoup
import os
def download_image(url, save_path):
response = requests.get(url)
with open(save_path, 'wb') as f:
f.write(response.content)
def crawl_images(url, save_dir):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
image_tags = soup.find_all('img')
for image_tag in image_tags:
image_url = image_tag['src']
image_name = image_url.split('/')[-1]
save_path = os.path.join(save_dir, image_name)
download_image(image_url, save_path)
# 示例使用
url = 'https://example.com' # 网页url
save_dir = 'images' # 图片保存路径
crawl_images(url, save_dir)
```
在示例代码中,`crawl_images`函数接收一个URL和一个保存图片的目录作为参数。它使用requests库获取网页内容,然后使用BeautifulSoup库解析网页。通过查找所有的`<img>`标签,我们可以获取到图片的URL。然后,通过`download_image`函数下载图片并保存到指定的目录中。
请注意,这只是一个简单的示例程序,实际使用时可能需要添加异常处理、去重、限制访问频率等功能来提高稳定性和效率。此外,根据不同网站的爬取规则和法律法规,请确保遵守相关规定。