如何获取Google Drive文件的file sharing link?含Python批量实现方法
获取Google Drive文件共享链接的方法
一、是否可以获取Google Drive文件的共享链接?
当然可以,你可以通过手动操作或编程方式获取文件的共享链接。
手动获取步骤
- 打开Google Drive,找到目标文件
- 右键点击文件,选择「共享」
- 在弹出窗口中点击「获取链接」
- 设置共享权限(如「任何人可查看」),复制生成的链接即可
二、使用Python批量获取所有文件的共享链接
要批量获取,需借助Google Drive API,以下是具体实现步骤:
准备工作
- 登录Google Cloud控制台,启用Google Drive API
- 创建服务账号,下载JSON格式的凭据文件(命名为
credentials.json) - 安装依赖包:
pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
代码示例
from google.oauth2 import service_account from googleapiclient.discovery import build # API配置 SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] SERVICE_ACCOUNT_FILE = 'credentials.json' # 初始化服务 credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES) drive_service = build('drive', 'v3', credentials=credentials) def fetch_all_share_links(): # 批量获取文件列表(单次最多1000条) results = drive_service.files().list( pageSize=1000, fields="nextPageToken, files(id, name, webViewLink)").execute() items = results.get('files', []) if not items: print('未找到任何文件。') else: print('文件名 | 共享链接') print('--- | ---') for item in items: # 注意:需确保文件已设置合适的共享权限,否则链接无法公开访问 print(f"{item['name']} | {item['webViewLink']}") if __name__ == '__main__': fetch_all_share_links()
关键注意事项
- 需将服务账号的邮箱添加为目标Drive文件的协作者,确保API有权限访问
webViewLink即为文件的共享链接,若未设置共享权限,该链接仅对文件所有者可见- 若文件总数超过1000,需通过
nextPageToken参数实现分页查询
内容的提问来源于stack exchange,提问作者Roy
相关产品推荐
相关产品推荐

