使用python将google docs公共电子表格下载到csv

2024-05-07 01:07:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以使用wget从Google Docs下载CSV文件:

wget --no-check-certificate --output-document=locations.csv 'https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv'

但我不能用Python下载相同的csv:

import urllib2

request = urllib2.Request('https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv')
request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1284.0 Safari/537.13')
opener = urllib2.build_opener()
data = opener.open(request).read()
print(data)

结果是Google登录页面。我做错什么了?


Tags: csvkeyhttpscomdocsoutputdatarequest
3条回答

requests库很棒,是Python的HTTP请求的金标准,但是这种下载风格虽然还没有被弃用,但不太可能持久,特别是指下载链接风格。实际上,Google Drive API v2中的downloadUrl字段是already deprecated。目前公认的将Google表单导出为CSV的方法是使用(当前的)Google Drive API

那么为什么要使用Drive API呢?这不应该是给Sheets API的东西吗?好吧,Sheets API用于面向电子表格的功能,即数据格式化、列大小调整、创建图表、单元格验证等,而Drive API用于面向文件的功能,即导入/导出。

下面是一个complete cmd-line solution。(如果不使用Python,则可以将其用作伪代码并选择Google APIs Client Libraries支持的任何语言。)对于代码片段,假设最新的工作表名为inventory(忽略具有该名称的旧文件),并且DRIVE是API服务终结点:

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')

如果您的工作表很大,您可能需要将其分块导出--请参见this page了解如何执行操作。如果你对googleapi还不熟悉,我有一个(有点过时但是)用户友好的intro video给你。(之后还有两段视频可能也很有用。)

您没有存储cookies。

首先让我说,我完全赞同使用most-excellent ^{} library的建议。

但是,如果您需要在vanilla Python 2中执行此操作,那么问题在于Google正在通过HTTP 302重定向让您四处走动,它希望您记住它在每个响应中设置的cookies。当它检测到您没有存储cookies时,会将您重定向到登录页面。

默认情况下,urllib2.urlopen(或从build_opener返回的opener)将遵循302重定向,但它不会存储HTTP cookies。你得教你的开场白怎么做。就像这样:

>>> from cookielib import CookieJar
>>> from urllib2 import build_opener, HTTPCookieProcessor
>>> opener = build_opener(HTTPCookieProcessor(CookieJar()))
>>> resp = opener.open('https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv')
>>> data = resp.read()

如果可能的话,再次使用requests,但是如果不可能,标准库可以完成任务。

只需使用requests,这比使用urllib要好得多:

import requests
response = requests.get('https://docs.google.com/spreadsheet/ccc?key=0ArM5yzzCw9IZdEdLWlpHT1FCcUpYQ2RjWmZYWmNwbXc&output=csv')
assert response.status_code == 200, 'Wrong status code'
print(response.content)

你可以用

pip install requests

相关问题 更多 >