谢谢Ido Ran https://github.com/ido-ran/google-photos-api-python-quickstart/blob/master/quickstart.py's and brillb https://stackoverflow.com/a/54000367/8641798的例子,我终于也解决了我的问题。上面给出的一些文档链接不再有效。尝试增强上面的示例,我找到了该页面Google 照片 API https://developers.google.com/photos/library/reference/rest/v1/mediaItems最有用。它不仅记录了 API,还允许您以交互方式测试您的请求 - 如果没有这种测试功能,我可能永远无法让它工作。输入请求后,您可以看到 cURL、HTTP 或 JAVASCRIPT 中的编码示例 - 但没有 Python 的编码示例。
除了制作我的专辑列表之外,我还对
- 每个专辑的链接,
- 图像列表(在相册中或不在相册中),
- 链接到我的每个媒体项目以及查找它们的 URL
为了获得专辑的链接,您可以简单地通过检索来扩展上面的示例item['productUrl']
。然而,很多时候该 URL 在 Firefox、IE 或 Edge 中不起作用(非常简单地显示专辑后出现 404 错误),但在 Chrome 和 Opera 中却起作用(谁知道为什么)。
专辑封面照片的 URL 似乎更可靠:item['coverPhotoMediaItemId']
您可以在下面找到专辑的链接Info.
而不是使用albums
方法,您还可以访问sharedAlbums
(并指定results.get('sharedAlbums', [])
。我希望能够得到shareableUrl
,但从未找到过ShareInfo
资源作为结果的一部分。
对于图像列表,您可以选择两种方法:mediaItems.list
and mediaItems.search
。我不认为前者有用,因为它返回一长串all您的图像,而搜索允许按日期限制结果,但照片是拍摄的(未上传!)。还有一个get
and batchGet
,我从未尝试过,因为您需要知道 Google 照片赋予图像的项目 ID。
每种方法都有一个限制(pageSize
) 以获得要返回的最大条目数。如果超过这个数量,它还会发送一个pageToken
,您可以用来请求下一部分。
我最终想出了这个例子:
from os.path import join, dirname
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/photoslibrary.readonly'
store = file.Storage(join(dirname(__file__), 'token-for-google.json'))
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets(join(dirname(__file__), 'client_id.json', SCOPES))
creds = tools.run_flow(flow, store)
google_photos = build('photoslibrary', 'v1', http=creds.authorize(Http()))
day, month, year = ('0', '6', '2019') # Day or month may be 0 => full month resp. year
date_filter = [{"day": day, "month": month, "year": year}] # No leading zeroes for day an month!
nextpagetoken = 'Dummy'
while nextpagetoken != '':
nextpagetoken = '' if nextpagetoken == 'Dummy' else nextpagetoken
results = google_photos.mediaItems().search(
body={"filters": {"dateFilter": {"dates": [{"day": day, "month": month, "year": year}]}},
"pageSize": 10, "pageToken": nextpagetoken}).execute()
# The default number of media items to return at a time is 25. The maximum pageSize is 100.
items = results.get('mediaItems', [])
nextpagetoken = results.get('nextPageToken', '')
for item in items:
print(f"{item['filename']} {item['mimeType']} '{item.get('description', '- -')}'"
f" {item['mediaMetadata']['creationTime']}\nURL: {item['productUrl']}")