Как исправить "SpreadsheetNotFound" при взаимодействии Python с таблицами Google? - PullRequest
0 голосов
/ 04 августа 2020

Я пытаюсь получить доступ к данным в таблице Google и изменить их, используя Python. Мне не удается открыть электронную таблицу Google из Python. Я внимательно следил за различными руководствами и подготовил следующее перед написанием любого кода.

  • Включено Google Sheets API и Google Drive API на консоли GCP
  • Сгенерированные и загруженные учетные данные (JSON файл) из GCP Console
  • Электронная таблица: Общий доступ (доступ для редактирования) с адресом электронной почты клиента, найденным в JSON файле
  • Установлено gspread и oauth2client -> pip install gspread oauth2client

Ниже приведен код Python для взаимодействия с Google Таблицами. Цель строк 12 и 13 - вывести на консоль все данные из связанной таблицы Google.

 1    import gspread
 2    from oauth2client.service_account import ServiceAccountCredentials
 3
 4    scope = ["https://spreadsheets.google.com/feeds","https://www.googleapis.com/auth/spreadsheets","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
 5    creds = ServiceAccountCredentials.from_json_keyfile_name('Py-Sheets.json', scope)
 6    client = gspread.authorize(creds)
 7    
 8    print("Hello World")
 9
10    sheet = client.open("Test-Sheets").sheet1
11
12    sample = sheet.get_all_records()
13    print(sample)

Кажется, все работает нормально до строки 10 (выше), где я получаю ошибка: SpreadsheetNotFound. Вот ошибка полностью (ниже).

Traceback (most recent call last):
  File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/client.py", line 119, in open
    self.list_spreadsheet_files(title),
  File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/utils.py", line 97, in finditem
    return next((item for item in seq if func(item)))
StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "pysheets.py", line 10, in <module>
    sheet = client.open("Test-Sheets").sheet1
  File "/home/username/anaconda3/lib/python3.7/site-packages/gspread/client.py", line 127, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

Я также получил следующую ошибку по электронной почте.

DNS Error: 15698833 DNS type 'mx' lookup of python-spreadsheets-123456.iam.gserviceaccount.com responded with code NXDOMAIN Domain name not found: python-spreadsheets-123456.iam.gserviceaccount.com

Как исправить ошибку, возникшую после выполнения строки 10? Код почти такой же, как и тот, что я нашел в руководствах. Таблица названа в точности так, как я ввел client.open(). Должна ли электронная таблица находиться в определенной директории c GDrive, чтобы она могла быть расположена?

1 Ответ

0 голосов
/ 04 августа 2020

В качестве альтернативы можно открыть электронную таблицу по URL-адресу в Google Colab:

# Access Google Sheets as a data source.
from google.colab import auth
auth.authenticate_user()
import gspread
from oauth2client.client import GoogleCredentials
gc = gspread.authorize(GoogleCredentials.get_application_default())
# At this point, you will have a link printed in your output which will direct you to a sign-in page. Pick the relevant google account and copy the provided link. Paste it in the provided line at the output section.
 

# Load your dataframe

import pandas as pd
        
wb = gc.open_by_url('https://docs.google.com/spreadsheets/.....') # A URL of your workbook.
sheet1 = wb.worksheet('Sheet1') # Enter your sheet name.
original_df = sheet1.get_all_values()
df = pd.DataFrame(original_df)
df.head()
...