从 Confluence 获取 table 作为 JSON

Get table as JSON from Confluence

我正在尝试从 JSON 格式的 Confluence 页面获取 table 内容。这都是 SSO,所以我只能使用 API 密钥,而且我还没有找到使用请求库访问 Confluence 的方法。不幸的是,Confluence API 的输出是普通的 html.

这就是我目前所知道的。 Confluence 库能否以 JSON 格式输出 tables(而不是在字典中显示原始 html 代码)?

from atlassian import Confluence
import os

user = "me@myself.com"
api_key = os.environ['confluence_api_key']
server = "https://xxxxxx.atlassian.net"
api_url = "/rest/api/content"
page_id = "12345"

confluence = Confluence(url=server, username=user, password=api_key)
page = confluence.get_page_by_title("TEST", "page 1", expand="body.storage")
content = page["body"]["storage"]
print(content)

输出如下所示:

{'value': '<p>Something something.</p><p /><table data-layout="default" ac:local-id="xxx"><colgroup><col style="width: 226.67px;" /><col style="width: 226.67px;" /><col style="width: 226.67px;" /></colgroup><tbody><tr><th><p><strong>name</strong></p></th><th><p><strong>type</strong></p></th><th><p><strong>comment</strong></p></th></tr><tr><td><p>text1</p></td><td><p>varchar(10)</p></td><td><p /></td></tr><tr><td><p>123</p></td><td><p>int</p></td><td><p /></td></tr></tbody></table>', 'representation': 'storage', 'embeddedContent': [], '_expandable': {'content': '/rest/api/content/12345'}}

请求库出现 404 错误:

request_url = "{server}{api_url}/{page_id}?expand=body.storage".format(
    server=server, api_url=api_url, page_id=page_id
)

requestResponse = requests.get(request_url, auth=(user, api_key))

print(requestResponse.status_code)

为什么要直接使用请求库? atlassian python API 已经在使用它,为您省去一些工作。

这周我碰巧 运行 遇到了同样的问题,我不得不用 BeautifulSoup 解析 table。 我认为对于通用解决方案,最好将您的 tables 作为 Dataframes:

from atlassian import Confluence
import os
from bs4 import BeautifulSoup
import pandas as pd

user = "me@myself.com"
api_key = os.environ['confluence_api_key']
server = "https://xxxxxx.atlassian.net"

confluence = Confluence(url=server, username=user, password=api_key)
page = confluence.get_page_by_title("TEST", "page 1", expand="body.storage")
body = page["body"]["storage"]["value"]

tables_raw = [[[cell.text for cell in row("th") + row("td")]
                    for row in table("tr")]
                    for table in BeautifulSoup(body, features="lxml")("table")]

tables_df = [pd.DataFrame(table) for table in tables_raw]
for table_df in tables_df:
    print(table_df)

然后您可以使用 to_json 将 DataFrames 转换为 JSON,具体取决于您希望如何构建字典...

编辑:样式信息(和链接等其他标签)在这种情况下会丢失(我们只得到单元格的文本)所以如果您想在修改后更新页面内容请注意
此外,如果您想使用 table 内容作为字典键,您可能需要更改 row/column index