帮我用python写一个爬取东北大学官方网站的图片
时间: 2024-05-03 18:22:08 浏览: 10
以下是一个简单的Python程序,可以帮助您爬取东北大学官方网站的图片:
```python
import requests
from bs4 import BeautifulSoup
import os
# 设置要爬取的网站和目录
url = 'http://www.neu.edu.cn/'
folder_path = './neu_images/'
# 创建目录
if not os.path.exists(folder_path):
os.makedirs(folder_path)
# 发送HTTP请求
response = requests.get(url)
# 解析HTML内容
soup = BeautifulSoup(response.content, 'html.parser')
# 查找所有的img标签
for img in soup.find_all('img'):
# 获取图片链接
img_url = img.get('src')
if not img_url.startswith('http'):
img_url = url + img_url
# 发送HTTP请求并保存图片
response = requests.get(img_url)
with open(os.path.join(folder_path, os.path.basename(img_url)), 'wb') as f:
f.write(response.content)
```
该程序首先发送HTTP请求获取东北大学官方网站的HTML内容,然后使用BeautifulSoup解析HTML内容。程序查找所有的img标签,并获取其src属性,然后发送HTTP请求并保存图片到指定的目录中。运行该程序后,您将在指定的目录中看到所有的图片。