使用请求(或其他库)以CSV格式访问公共Google表格的内容 [英] Accessing the contents of a public Google Sheet as CSV using Requests (or other library)
问题描述
我编写了一个小型python程序,该程序可以处理CSV文件中的数据.我正在跟踪Google工作表中的一些数字,并通过下载Google工作表创建了CSV文件.我试图找到一种方法,让python直接从Google表格中直接读取CSV文件,以便在更新电子表格时不必下载新的CSV.
I wrote a small python program that works with data from a CSV file. I am tracking some numbers in a google sheet and I created the CSV file by downloading the google sheet. I am trying to find a way to have python read in the CSV file directly from google sheets, so that I do not have to download a new CSV when I update the spreadsheet.
我看到请求库也许可以处理这个问题,但是我很难弄清楚它.我选择不尝试使用google API,因为只要我不介意将表格公开给那些具有链接的人,这种方法就更简单了.
I see that the requests library may be able to handle this, but I'm having a hard time figuring it out. I've chosen not to try the google APIs because this way seems simpler as long as I don't mind making the sheet public to those with the link, which is fine.
我曾尝试使用请求文档,但我是一名新手程序员,因此无法以CSV格式读取它.
I've tried working with the requests documentation but I'm a novice programmer and I can't get it to read in as a CSV.
这是当前将数据导入python的方式:
This is how the data is currently taken into python:
file = open('data1.csv', newline='')
reader = csv.reader(file)
我希望file = open()
在理想情况下可以被请求库替换并直接从电子表格中提取.
I would like the file = open()
to ideally be replaced by the requests library and pull directly from the spreadsheet.
推荐答案
您需要找到下载文件的正确URL请求.
You need to find the correct URL request that download the file.
示例网址:
csv_url='https://docs.google.com/spreadsheets/d/169AMdEzYzH7NDY20RCcyf-JpxPSUaO0nC5JRUb8wwvc/export?format=csv&id=169AMdEzYzH7NDY20RCcyf-JpxPSUaO0nC5JRUb8wwvc&gid=0'
做到这一点的方法是在浏览器的开发人员工具的网络"选项卡中检查请求URL的同时手动下载文件.
The way to doing it is by manually download your file while inspecting the requests URL at the Network tab in the Developer Tools in your browser.
那么以下内容就足够了:
Then the following is enough:
import requests as rs
csv_url=YOUR_CSV_DOWNLOAD_URL
res=rs.get(url=csv_url)
open('google.csv', 'wb').write(res.content)
它将名称为'google.csv'
的CSV文件保存在python脚本文件的文件夹中.
It will save CSV file with the name 'google.csv'
in the folder of you python script file.
这篇关于使用请求(或其他库)以CSV格式访问公共Google表格的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!