Authenticate to Google Drive and download spreadsheet with Python urllib2 requests

0 votes

I want to download a document from my Google Drive that verifies my Google account (I only want certain users to be able to access it and do not want to publish it on the web). I've tried using requests, but it seems like I'm doing something incorrectly. By navigating to the URL https://docs.google.com/spreadsheets/d/document key>/export?format=xls in a browser, I may download my document.

So in my python script :

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)

However, the resulting document.xls is empty.

What am I doing wrong?

Sep 26, 2022 in Others by Kithuzzz
• 29,080 points
165 views

1 answer to this question.

0 votes

Your goal may be feasible, but the following reasons (which are by no means all of them) make it unlikely that it will be simple:

  1. Google is usually blocking user-agents that are non-browsers(like your Python script) for browser-intended content (for security reasons); you would have to spoof it, which is actually easy
  2. Multi-factor authentication - you would have to turn that off (easy, but you open yourself up for being hacked...)
  3. Session-cookie - aka security cookie; (not so easy to get ahold of)

What you should do instead

Use the official google-drive API. Also, the Python client library has a nice tutorial and this page describes how to download files from google drive.

If you want to write even less code, then libraries like PyDrive will make you are living even easier.

 

answered Sep 27, 2022 by narikkadan
• 53,920 points

Related Questions In Others

0 votes
1 answer
0 votes
0 answers
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 3,329 views
0 votes
1 answer
0 votes
1 answer

How to insert info into online excel spreadsheet with python selenium

I recently discovered one of my options, ...READ MORE

answered Oct 24, 2022 in Others by narikkadan
• 53,920 points
225 views
0 votes
1 answer

How to format numbers as lakhs and crores in excel/ google spreadsheet when the number could be negative too?

Excel formatting, in my opinion, can only ...READ MORE

answered Oct 31, 2022 in Others by narikkadan
• 53,920 points
1,466 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP