Skip to content

Instantly share code, notes, and snippets.

@shadiakiki1986
Last active August 25, 2021 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shadiakiki1986/f74e29fa2d49392019e7a4df356089c7 to your computer and use it in GitHub Desktop.
Save shadiakiki1986/f74e29fa2d49392019e7a4df356089c7 to your computer and use it in GitHub Desktop.
Download file from gdrive in R, python, bash
# python equivalent to get file from gdrive
fileid="123451234sdfgsdfg"
filename="filename.txt"
import requests
s = requests.Session()
# all cookies received will be stored in the session object
r=s.get(f'https://docs.google.com/uc?export=download&id={fileid}')
import re
conf_code = re.sub(".*confirm=([0-9A-Za-z_]+).*$", "\\1", r.text).split("\n")[1]
response = s.get(f'https://docs.google.com/uc?export=download&id={fileid}&confirm={conf_code}')
file = open(filename, "w")
file.write(response.text)
file.close()
# Based on https://www.matthuisman.nz/2019/01/download-google-drive-files-wget-curl.html
# Example usage: get_gdrive(fileid="12345", destfile="file.txt")
get_gdrive <- function(fileid, destfile) {
handle = curl::new_handle()
myurl=sprintf("https://docs.google.com/uc?export=download&id=%s", fileid)
destconf="confirm.txt"
curl::curl_download(myurl, destconf, handle = handle)
conf=readLines(destconf)
conf_code = gsub(".*confirm=([0-9A-Za-z_]+).*", "\\1", conf)[2]
print(conf_code)
myurl=sprintf("https://docs.google.com/uc?export=download&id=%s&confirm=%s", fileid, conf_code)
curl::curl_download(myurl, destfile, handle = handle)
}
# This is a copy of the original bash wget code from the source website
# https://www.matthuisman.nz/2019/01/download-google-drive-files-wget-curl.html
cd ~
export fileid=1sNhrr2u6n48vb5xuOe8P9pTayojQoOc_
export filename=combian.rar
## WGET ##
wget --save-cookies cookies.txt 'https://docs.google.com/uc?export=download&id='$fileid -O- \
| sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1/p' > confirm.txt
wget --load-cookies cookies.txt -O $filename \
'https://docs.google.com/uc?export=download&id='$fileid'&confirm='$(<confirm.txt)
## CURL ##
curl -L -c cookies.txt 'https://docs.google.com/uc?export=download&id='$fileid \
| sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1/p' > confirm.txt
curl -L -b cookies.txt -o $filename \
'https://docs.google.com/uc?export=download&id='$fileid'&confirm='$(<confirm.txt)
rm -f confirm.txt cookies.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment