使用Colab笔记本获取Google驱动器中文件的共享链接

时间:2019-11-20 15:39:18

标签: python url google-drive-api google-colaboratory

有人可以告诉我如何使用Colab笔记本自动获取Google驱动器中文件的共享链接吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

如果您查看documentation,则会看到一个部分,说明如何从云端硬盘列出文件。

使用该代码并阅读documentation of the library used,我创建了以下脚本:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

files = drive.ListFile().GetList()
for file in files:
  keys = file.keys()
  if 'webContentLink' in keys:
    link = file['webContentLink']
  elif 'webViewLink' in keys:
    link = file['webViewLink']
  else:
    link = 'No Link Available. Check your sharing settings.'

  if 'name' in keys:
    name = file['name']
  else:
    name = file['id']

  print('name: {}  link: {}'.format(name, link))

这当前列出了所有文件并提供了指向该文件的链接。

然后您可以编辑函数以查找特定文件。

希望这会有所帮助!

答案 1 :(得分:0)

您可以使用xattr来获取file_id

from subprocess import getoutput
from IPython.display import HTML
from google.colab import drive
drive.mount('/content/drive')  # access drive
# need to install xattr
!apt-get install xattr > /dev/null
# get the id
fid = getoutput("xattr -p 'user.drive.id' /content/drive/My\\ Drive/Colab\\ Notebooks/R.ipynb")
# make a link and display it
HTML(f"<a href=https://colab.research.google.com/drive/{fid} target=_blank>notebook</a>")

我在这里访问/Colab Notebooks/R.ipynb上的笔记本文件,并创建一个链接以在Colab中打开它。