从 Confluence 获取 JSON 格式的表格

问题描述 投票:0回答:1

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

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

from atlassian import Confluence
import os

user = "[email protected]"
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)
python confluence confluence-rest-api
1个回答
4
投票

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

我这周碰巧遇到了同样的问题,我不得不用 BeautifulSoup 解析表格。 我认为对于通用解决方案,最好将您的表格作为数据框:

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

user = "[email protected]"
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,具体取决于您想要如何构建字典...

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

EDIT2:这是一个古老的答案,但由于它最近被投票,我只想补充一点,在这种情况下,

tables_raw
可以使用内置的 pandas
read_html

tables_df = pd.read_html(body)

这甚至会直接将表头设置为 df 列名,并具有提取链接或解析日期的参数。但是,特别是如果您在 df 中需要的不仅仅是

cell.text
(在我最初的情况下我想导入图标),上面的答案仍然有效。

© www.soinside.com 2019 - 2024. All rights reserved.