ภาษา Python เป็นภาษาหนึ่งที่สามารถทำได้หลายอย่าง และสำหรับใครที่จะทำการอัพโหลดไฟล์ หรือดาวน์โหลดโดยการนำลิ้งที่ share ของ google drive สามารถนำเอาวิธีหรือโค้ดคำสั่งนี้นำไปประยุกต์ หรือใช้งานได้ ในการทำงานของวิธีนี้จะใช้การ request เข้ามาจัดดังนั้นก็ต้องใช้ librarry ของ Python ที่มีชื่อว่า requests โดยจะต้องทำการติดตั้งตัวนี้ขึ้นมาก่อน
คำสั่งในการติดตั้ง requests
โค้ด: เลือกทั้งหมด
pip install requests
โค้ด: เลือกทั้งหมด
def download_googledrive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params = { 'id' : id }, stream = True)
head_r=response.headers
content_dis=head_r['Content-Disposition']
content_dis=content_dis.split(';')
for index in range(len(content_dis)):
if content_dis[index].split('=')[0] =='filename':
filename = content_dis[index].split('=')[1]
filename = filename.split('"')[1]
destination=destination + filename
save_file(response, destination)
return filename
โค้ด: เลือกทั้งหมด
def save_file(response, destination):
CHUNK_SIZE = 32768
with open(destination, "wb") as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
โค้ด: เลือกทั้งหมด
url = 'https://drive.google.com/open?id=1Yn1vi-2diTLXikdF7iYA7WYe213rfVJl'
url = url.split('?')[1]
file_id=url.split('=')[1]
pathfile = 'file/'
โค้ด: เลือกทั้งหมด
import requests
def download_googledrive(id, destination):
URL = "https://docs.google.com/uc?export=download"
session = requests.Session()
response = session.get(URL, params = { 'id' : id }, stream = True)
head_r=response.headers
content_dis=head_r['Content-Disposition']
content_dis=content_dis.split(';')
for index in range(len(content_dis)):
if content_dis[index].split('=')[0] =='filename':
filename = content_dis[index].split('=')[1]
filename = filename.split('"')[1]
destination=destination + filename
save_file(response, destination)
return filename
def save_file(response, destination):
CHUNK_SIZE = 32768
with open(destination, "wb") as f:
for chunk in response.iter_content(CHUNK_SIZE):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
url = 'https://drive.google.com/open?id=1Yn1vi-2diTLXikdF7iYA7WYe213rfVJl'
url = url.split('?')[1]
file_id=url.split('=')[1]
pathfile = 'file/'
file_down=download_googledrive(file_id, pathfile)
print 'Download file :'+file_down+'success'
ผลที่ได้
จากนั้นสังเกตที่ path ที่เก็บไฟล์จะมีไฟล์เพิ่มเข้ามา
ผลที่ได้
อ้างอิง
https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url
https://www.codementor.io/aviaryan/downloading-files-from-urls-in-python-77q3bs0un
https://code.tutsplus.com/tutorials/how-to-download-files-in-python--cms-30099