<p><code>requests</code>库很棒,是Python的HTTP请求的金标准,但是这种下载风格虽然还没有被弃用,但不太可能持久,特别是指下载链接风格。实际上,<a href="http://developers.google.com/drive/v2/web/" rel="nofollow noreferrer">Google Drive API v2</a>中的<code>downloadUrl</code>字段是<a href="https://developers.google.com/drive/v3/web/migration#fields" rel="nofollow noreferrer">already deprecated</a>。目前公认的将Google表单导出为CSV的方法是使用(当前的)<a href="http://developers.google.com/drive" rel="nofollow noreferrer">Google Drive API</a>。</p>
<p>那么为什么要使用Drive API呢?这不应该是给<a href="http://developers.google.com/sheets" rel="nofollow noreferrer">Sheets API</a>的东西吗?好吧,Sheets API用于面向电子表格的功能,即数据格式化、列大小调整、创建图表、单元格验证等,而Drive API用于面向文件的功能,即导入/导出。</p>
<p>下面是一个<a href="http://wescpy.blogspot.com/2016/07/exporting-google-sheet--as-csv.html" rel="nofollow noreferrer">complete cmd-line solution</a>。(如果不使用Python,则可以将其用作伪代码并选择<a href="http://developers.google.com/discovery/libraries" rel="nofollow noreferrer">Google APIs Client Libraries</a>支持的任何语言。)对于代码片段,假设最新的工作表名为<code>inventory</code>(忽略具有该名称的旧文件),并且<code>DRIVE</code>是API服务终结点:</p>
<pre><code>FILENAME = 'inventory'
SRC_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
DST_MIMETYPE = 'text/csv'
# query for latest file named FILENAME
files = DRIVE.files().list(
q='name="%s" and mimeType="%s"' % (FILENAME, SRC_MIMETYPE),
orderBy='modifiedTime desc,name').execute().get('files', [])
# if found, export Sheets file as CSV
if files:
fn = '%s.csv' % os.path.splitext(files[0]['name'].replace(' ', '_'))[0]
print('Exporting "%s" as "%s"... ' % (files[0]['name'], fn), end='')
data = DRIVE.files().export(fileId=files[0]['id'], mimeType=DST_MIMETYPE).execute()
# if non-empty file
if data:
with open(fn, 'wb') as f:
f.write(data)
print('DONE')
</code></pre>
<p>如果您的工作表很大,您可能需要将其分块导出--请参见<a href="http://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents" rel="nofollow noreferrer">this page</a>了解如何执行<em>和</em>操作。如果你对googleapi还不熟悉,我有一个(有点过时但是)用户友好的<a href="http://youtu.be/DYAwYxVs2TI?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq&index=2" rel="nofollow noreferrer">intro video</a>给你。(之后还有两段视频可能也很有用。)</p>