代码如下。这不是完整的代码,但是它的基础。我试图从Twitter的API中获取数据,并将其写入我的Google Sheets API。以下是代码:
from googleapiclient import discovery
from google.oauth2 import service_account
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
SERVICE_ACCOUNT_FILE = 'twitter.json' #json File should be in the same folder as this Python Script.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg'
#SAMPLE_RANGE_NAME = 'Class Data!A2:A60'
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
# Call the Sheets API
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range='twitterData!A1:A180').execute()
#ERROR HERE BELOW
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
我得到一个错误的一行有上面的注释下面的错误。这是错误信息:
Traceback (most recent call last):
File "C:UsersJohn DoeDesktopCodePythonTwittertest.py", line 27, in <module>
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
File "C:UsersJohn DoeAppDataLocalProgramsPythonPython38-32libsite-packagesgoogleapiclient_helpers.py", line 130, in positional_wrapper
return wrapped(*args, **kwargs)
File "C:UsersJohn DoeAppDataLocalProgramsPythonPython38-32libsite-packagesgoogleapiclienthttp.py", line 938, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 400 when requesting https://sheets.googleapis.com/v4/spreadsheets/1f4iqVHljytmRSC2EZcApEiA2lE1cHa1o6Fr4s3t0AKg/values/twitterData%21B2%3AB180?valueInputOption=USER_ENTERED&alt=json returned "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8". Details: "[{'@type': 'type.googleapis.com/google.rpc.BadRequest', 'fieldViolations': [{'field': 'data.values', 'description': "Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"}]}]">
我以前用过Google Sheets API。我不知道为什么这个代码不工作。就这一行。
我认为你们现在发行的"Invalid value at 'data.values' (type.googleapis.com/google.protobuf.ListValue), 8"
的原因是由于body={"values": 8}
。在这种情况下,需要使用二维数组。所以,请修改如下:
:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID,
range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": 8}).execute()
:
request = sheet.values().update(spreadsheetId = SAMPLE_SPREADSHEET_ID, range = 'twitterData!B2:B180', valueInputOption='USER_ENTERED', body={"values": [[8]]}).execute()
- 本次修改将
body={"values": 8}
修改为body={"values": [[8]]}
。 - 通过这个修改,
8
被放到单元格"b2";";twitterData"表。 参考:
- 方法:spreadsheets.values.update