欢迎访问宙启技术站
智能推送

利用Python抓取阿里云盘资源

发布时间:2023-05-17 10:22:20

阿里云盘是阿里云旗下的一个云存储平台,提供了文件存储、文件管理和文件分享等功能。其提供了API接口,可以通过Python的requests库进行调用,实现文件的上传、下载、删除和查询等操作。

1. 获取access_token

使用Python调用阿里云盘API接口需要先获取access_token,具体步骤如下:

1.1 登录阿里云盘,在“我的”-“开发者中心”中创建应用。

1.2 在创建应用时,需要设置应用回调地址。回调地址可随意设置,只需保证应用设置和代码中一致即可。

1.3 创建应用成功后,可以获取到access_key和access_secret。将这两个参数保存在一个config.ini的配置文件中,方便后续调用。

1.4 通过API接口获取access_token:

import configparser
import requests

config = configparser.ConfigParser()
config.read('config.ini')
access_key = config['aliyun']['access_key']
access_secret = config['aliyun']['access_secret']

url = 'https://oauth.aliyun.com/v1/token'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
    'grant_type': 'client_credentials',
    'client_id': access_key,
    'client_secret': access_secret
}

response = requests.post(url, headers=headers, data=data)
print('access_token:', response.json()['access_token'])

2. 文件的上传、下载和删除

2.1 文件上传

文件上传需要指定上传文件的路径和阿里云盘的文件夹路径。上传成功后会返回文件的file_id。

import configparser
import requests

config = configparser.ConfigParser()
config.read('config.ini')
access_token = config['aliyun']['access_token']

url = 'https://api.aliyundrive.com/v2/file/create'
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

filepath = '/Users/xxx/Desktop/image.png'
folder_path = '/test'

params = {
    'drive_id': '******',
    'parent_file_id': 'root',
    'name': 'image.png',
    'size': os.path.getsize(filepath),
    'type': 'file',
    'check_name_mode': 'refuse'
}
data = {
    'part_info_list': []
}
response = requests.post(url, headers=headers, params=params, json=data)

file_id = response.json()['file_id']
upload_url = response.json()['part_info_list'][0]['upload_url']
upload_id = response.json()['part_info_list'][0]['upload_id']

with open(filepath, 'rb') as f:
    content = f.read()
    headers = {
        'Content-Type': 'multipart/form-data',
        'Content-Length': str(len(content)),
        'Content-MD5': hashlib.md5(content).hexdigest(),
        'Content-Disposition': 'form-data',
        'x-ali-byte-range': '0-' + str(len(content) - 1) + '/'+ str(len(content)),
        'Connection': 'Keep-Alive'
    }
    response = requests.put(upload_url, headers=headers, data=content)

print('file_id:', file_id)

2.2 文件下载

文件下载需要指定文件的file_id和下载文件的路径。下载成功后会将文件保存在指定的路径中。

import configparser
import requests

config = configparser.ConfigParser()
config.read('config.ini')
access_token = config['aliyun']['access_token']

url = 'https://api.aliyundrive.com/v2/file/downloadurl'
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

file_id = '***********'
params = {
    'file_id': file_id,
    'expire_sec': '3600'
}
response = requests.get(url, headers=headers, params=params)

download_url = response.json()['url']
response = requests.get(download_url)

filepath = '/Users/xxx/Desktop/download.png'
with open(filepath, 'wb') as f:
    f.write(response.content)

print('download success')

2.3 文件删除

文件删除需要指定文件的file_id。

import configparser
import requests

config = configparser.ConfigParser()
config.read('config.ini')
access_token = config['aliyun']['access_token']

url = 'https://api.aliyundrive.com/v2/file/delete'
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

file_id = '***********'
params = {
    'check_size': True,
    'drive_id': '******',
    'file_id': file_id
}
response = requests.post(url, headers=headers, json=params)

print('delete success')

3. 文件的查询

文件的查询需要指定查询的文件夹路径和文件名。查询成功后会返回该文件夹下的所有文件信息。

import configparser
import requests

config = configparser.ConfigParser()
config.read('config.ini')
access_token = config['aliyun']['access_token']

url = 'https://api.aliyundrive.com/v2/file/search'
headers = {
    'Authorization': 'Bearer ' + access_token,
    'Content-Type': 'application/json'
}

folder_path = '/test'
file_name = 'image.png'

params = {
    'drive_id': '******',
    'url_decode': True,
    'image_thumbnail_process': '{"mode":0,"width":100,"height":100,"quality":50}',
    'source': 'all',
    'type': 'file,folder',
    'limit': 10,
    'name': file_name,
    'parent_file_id': 'root',
    'order_by': 'updated_at',
    'order_direction': 'DESC',
    'all': False,
    'file_id': '',
    'image_url_process': '',
    'video_thumbnail_process': ''
}
response = requests.get(url, headers=headers, params=params)

if response.json()['items']:
    file_id = response.json()['items'][0]['file_id']
    print('file_id:', file_id)
else:
    print(file_name, 'not found')

综上所述,可以通过Python调用阿里云盘API接口对文件进行上传、下载、删除和查询等操作。