【问题标题】:How would I get the ID of a created file using python and the Google Docs API?如何使用 python 和 Google Docs API 获取创建文件的 ID?
【发布时间】:2020-01-29 01:07:13
【问题描述】:

我正在编写一个简单的 python 程序来收集信息并将其格式化为谷歌文档。我希望程序创建文档,然后向其中添加文本。我可以轻松地创建一个程序,并且我在向现有文档中添加文本时没有遇到任何问题。但是,我无法在程序中访问已创建文档的 ID,因此无法向其中添加文本。如何获取在我想要编辑的同一程序中创建的文档的 ID?

【问题讨论】:

  • 您可以发布您尝试过的代码示例吗?使用 API 创建 Google 文档有多种方法 - Drive 和 Docs(和 Sheets)API 都具有创建文档功能。
  • 当然。这是我用来创建文档的内容:doc = docsService.documents().create(body=body).execute() 这或多或少与 API 参考的“创建文档”部分中的描述完全一致。但是,同一参考文献中的“插入文本”部分包含以下行:result = docsService.documents().batchUpdate(documentId=, body={'requests': requests}).execute() 执行,这需要一个文档 ID,如果不手动打开文档并从 URL 复制,我似乎无法获得。
  • 你有对象 doc,所以要获取文档 ID,你只需要调用 docId = doc.get('documentId')
  • 啊,我只是个白痴。出于某种原因,我尝试使用“get(‘docId’)”。谢谢!

标签: python google-docs-api


【解决方案1】:

按照以下链接中记录的步骤 1 和 2 进行操作:
https://developers.google.com/docs/api/quickstart/python

然后试试下面的代码:

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
SCOPES = ['https://www.googleapis.com/auth/documents']
creds = None

if os.path.exists('token.pickle'):
  with open('token.pickle', 'rb') as token:
    creds = pickle.load(token)

# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
  if creds and creds.expired and creds.refresh_token:
    creds.refresh(Request())
  else:
    flow = InstalledAppFlow.from_client_secrets_file('/content/credentials.json', SCOPES)
    #creds = flow.run_local_server(port=0)
    creds = flow.run_console()
  # Save the credentials for the next run
  with open('token.pickle', 'wb') as token:
      pickle.dump(creds, token)

service = build('docs', 'v1', credentials=creds)

title = 'My Test Document'
body = {
    'title': title
}
doc = service.documents().create(body=body).execute()
docId = doc.get('documentId')
print( 'Id of new Document is : ' + docId )


注意: 将文件credentials.json 放在适当的位置,并在代码中相应地设置路径。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多