如何使用 Python 从 Google 文档中提取或读取图像

How to extract or read Image from Google Doc using Python

我正在尝试从我的 google 文档中读取数据。所以我现在正在使用 python,我已经实现了 Google Docs API 并使用了 python。我只是复制粘贴了 google 提供的代码并做了一些修改,我成功地读取了数据 LINE BY LINE 但是 TEXT ONLY!现在我正在尝试新的东西并插入了一张图片。这是它的样子。

Google Doc Link

非常简单吧...它有一个要点和包含图像和“你好”文本的子要点。现在,当我读取数据(它逐行读取)时,我尝试再次打印出 API returns 和 returns 包含 dictionariesdictionary .这是它的样子。

{'startIndex': 1, 'endIndex': 41, 'paragraph': {'elements': [{'startIndex': 1, 'endIndex': 41, 'textRun': {'content': 'This is the Python Programming Language\n', 'textStyle': {}}}], 'paragraphStyle': {'namedStyleType': 'NORMAL_TEXT', 'direction': 'LEFT_TO_RIGHT', 'indentFirstLine': {'magnitude': 18, 'unit': 'PT'}, 'indentStart': {'magnitude': 36, 'unit': 'PT'}}, 'bullet': {'listId': 'kix.y7w314ij0ywy', 'textStyle': {'underline': False}}}}


{'startIndex': 41, 'endIndex': 43, 'paragraph': {'elements': [{'startIndex': 41, 'endIndex': 42, 'inlineObjectElement': {'inlineObjectId': 'kix.o4cuh6wash2n', 'textStyle': {}}}, {'startIndex': 42, 'endIndex': 43, 'textRun': {'content': '\n', 'textStyle': {}}}], 'paragraphStyle': {'namedStyleType': 'NORMAL_TEXT', 'direction': 'LEFT_TO_RIGHT', 'indentFirstLine': {'magnitude': 54, 'unit': 'PT'}, 'indentStart': {'magnitude': 72, 'unit': 'PT'}}, 'bullet': {'listId': 'kix.y7w314ij0ywy', 'nestingLevel': 1, 'textStyle': {'underline': False}}}}


{'startIndex': 43, 'endIndex': 49, 'paragraph': {'elements': [{'startIndex': 43, 'endIndex': 49, 'textRun': {'content': 'Hello\n', 'textStyle': {}}}], 'paragraphStyle': {'namedStyleType': 'NORMAL_TEXT', 'direction': 'LEFT_TO_RIGHT', 'indentFirstLine': {'magnitude': 54, 'unit': 'PT'}, 'indentStart': {'magnitude': 72, 'unit': 'PT'}}, 'bullet': {'listId': 'kix.y7w314ij0ywy', 'nestingLevel': 1, 'textStyle': {'underline': False}}}}

如您所见,有 3 个词典包含 keyvalue 对。请注意,这三个是文档中的每一行。正如您还可以观察到的那样,键 content 及其 value(s) 是文档中的文本。

如果您查看嵌套词典,它是这些:

{'content': 'This is the Python Programming Language\n', 'textStyle': {}}
{'content': '\n', 'textStyle': {}}
{'content': 'Hello\n', 'textStyle': {}}

现在我注意到它为图像包含的行返回了 \n。我还寻找了至少它可能有一个 key 并且它的值将是图像的临时 url 但它似乎没有那个。所以我的问题是有没有办法使用我正在使用的 API 以某种方式读取此图像(也提取它)?可能我只是错过了一些东西......有人可以帮我吗?任何其他替代解决方案将不胜感激!谢谢!

顺便说一句,这里是 google 提供的源代码,我已经对 read_strucutural_elements 函数进行了修改,以了解它如何为我个人目的读取数据,但如您所见这就是它的工作原理,其中 API returns 每行数据的字典。我还注意到 API 确实确实逐行读取它 returns 其中的 dictionary

def main():
    """Shows basic usage of the Docs API.
    Prints the title of a sample document.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    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(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

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

    # Retrieve the documents contents from the Docs service.
    document = service.documents().get(documentId=DOCUMENT_ID).execute()

    #print('The title of the document is: {}'.format(document.get('title')))
    data = read_strucutural_elements(document.get("body").get("content"))

这是 read_strucutural_elements 函数,我只是在那里打印出 elements 参数中的元素,其中该参数逐行包含这些数据。

def read_strucutural_elements(elements):

    for value in elements:
        print(value) #the value of the value variable is the nested dictionaries I've shown above
        print()

非常感谢!

查看字典输出,图像是具有特定 id 的 inlineObject。您应该能够使用其 url 检索图像。要获得 url,请参阅相关问题: