使用Python urllib2 /请求对Google云端硬盘进行身份验证并下载电子表格

luc*_*one 4 python excel http download python-requests

我想下载我在Google云端硬盘中向Google验证的文档(我只希望某些用户能够访问它并且不想在网上发布它).

我尝试过使用,requests但显然我做错了.从浏览器我可以将我的文档下载到该地址 https://docs.google.com/spreadsheets/d/<document key>/export?format=xls.

所以在我的python脚本中,我执行以下操作:

import os
import requests
import shutil
from requests.auth import HTTPBasicAuth

remote = "https://docs.google.com/spreadsheets/d/<document key>/export?format=xls"
username = os.environ['GOOGLEUSERNAME']
password = os.environ['GOOGLEPASSWORD']
r = requests.get(remote, auth=HTTPBasicAuth(username,password))
if r.status_code == 200:
  with open("document.xls","wb") as f:
    shutil.copyfileobj(r.raw, f)
Run Code Online (Sandbox Code Playgroud)

但结果document.xls是空的.

我究竟做错了什么?

Mar*_*kov 5

它实际上可能是你想要做的事情,但是这里有一些原因,它将是非平凡的(绝不是一个完整的列表):

  1. user-agents对于浏览器目的内容,Google通常会阻止非浏览器(如Python脚本)(出于安全原因); 你必须欺骗它,这实际上很容易
  2. 多因素身份验证 - 您必须将其关闭(很容易,但是您可能会被黑客攻击...)
  3. 会话cookie - akasecurity cookie ; (不容易得到)

你应该做什么

使用官方的google-drive API.此外,Python客户端库有一个很好的教程,这个页面描述了如何从谷歌驱动器下载文件.

如果你想编写更少的代码,那么像PyDrive这样的库将使你的生活更加轻松.

希望这可以帮助!