使用python爬取https://www.kaggle.com/datasets/sudhanshu2198/oil-spill-detection上的数据集,并保存在本地文件中,给出详细代码...
时间: 2023-08-22 10:07:22 浏览: 271
Data Source : Kaggle Data Source Link : https://www.kaggle.com/
好的,以下是使用Python爬取该数据集并保存在本地的代码:
```python
import requests
import os
# 目标数据集的URL
url = "https://www.kaggle.com/datasets/sudhanshu2198/oil-spill-detection"
# 设置请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"}
# 发送请求
response = requests.get(url, headers=headers)
# 解析HTML文档
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
# 查找下载链接
download_links = []
a_tags = soup.find_all("a")
for a in a_tags:
if "Download" in a.text:
download_links.append(a["href"])
# 创建保存目录
save_dir = "oil-spill-detection"
if not os.path.exists(save_dir):
os.mkdir(save_dir)
# 下载并保存文件
for link in download_links:
file_name = link.split("/")[-1]
file_path = os.path.join(save_dir, file_name)
with open(file_path, "wb") as f:
f.write(requests.get(link, headers=headers).content)
print(f"Saved {file_name}")
```
这段代码会向目标数据集的URL发送请求,解析HTML文档,查找下载链接,并下载保存数据集中的文件到本地。下载的文件会保存在名为“oil-spill-detection”的文件夹中。请注意,该代码运行时需要安装requests和BeautifulSoup库。
阅读全文