
在日常工作中,我们经常需要从Confluence页面中提取特定的信息,例如存储在表格中的结构化数据。对于Python开发者而言,实现这一目标主要有两种途径:一是通过Confluence官方提供的REST API,二是在特定条件下直接访问Confluence的后端数据库。本教程将详细解析这两种方法,并提供相应的指导和建议。
Confluence REST API是Atlassian官方推荐的数据交互方式,它提供了一套稳定且易于使用的接口,允许开发者以编程方式访问和操作Confluence内容。对于从Confluence页面提取表格数据,API是首选方案,因为它抽象了底层数据库的复杂性,并能兼容云端和自托管的Confluence实例。
在使用Confluence REST API之前,您需要获取一个API令牌(对于云端Confluence)或使用基本认证(用户名和密码,对于自托管Confluence)。
要提取页面内容,您通常需要使用获取页面内容的API端点。Confluence页面内容通常以存储格式(Storage Format,即XHTML)返回。
立即学习“Python免费学习笔记(深入)”;
以下是一个使用Python的requests库和BeautifulSoup库来从Confluence页面提取表格数据的示例。
首先,确保安装了必要的库:
pip install requests beautifulsoup4
然后,编写Python代码:
import requests
from bs4 import BeautifulSoup
import base64
import json
# Confluence 配置
CONFLUENCE_BASE_URL = "https://your-confluence-domain.atlassian.net" # 或 "http://your-self-hosted-confluence.com"
API_USERNAME = "your_email@example.com" # 或您的Confluence用户名
API_TOKEN = "YOUR_API_TOKEN" # 或您的Confluence密码,如果是自托管
# 要提取数据的Confluence页面ID
PAGE_ID = "123456789" # 替换为实际的页面ID
def get_confluence_page_content(page_id):
"""
通过Confluence REST API获取指定页面的内容(存储格式)。
"""
url = f"{CONFLUENCE_BASE_URL}/wiki/rest/api/content/{page_id}?expand=body.storage"
# 构建认证头
# 对于云端Confluence,使用API令牌
# 对于自托管Confluence,使用用户名和密码
headers = {
"Accept": "application/json",
"Authorization": f"Basic {base64.b64encode(f'{API_USERNAME}:{API_TOKEN}'.encode()).decode()}"
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 检查HTTP请求是否成功
data = response.json()
# 提取页面的存储格式内容
storage_content = data.get('body', {}).get('storage', {}).get('value')
if storage_content:
return storage_content
else:
print(f"Page {page_id} has no storage content or content is empty.")
return None
except requests.exceptions.RequestException as e:
print(f"Error fetching Confluence page {page_id}: {e}")
return None
def extract_table_data(html_content):
"""
从HTML内容中解析并提取所有表格数据。
"""
if not html_content:
return []
soup = BeautifulSoup(html_content, 'html.parser')
tables = soup.find_all('table')
all_extracted_tables = []
for i, table in enumerate(tables):
table_data = []
rows = table.find_all('tr')
# 提取表头
header_row = rows[0] if rows else None
headers = [th.get_text(strip=True) for th in header_row.find_all(['th', 'td'])] if header_row else []
if headers:
table_data.append(headers)
# 提取数据行
for row in rows[1:]: # 跳过表头行
cols = row.find_all(['td', 'th']) # td for data, th for potential row headers
cols = [ele.get_text(strip=True) for ele in cols]
table_data.append(cols)
if table_data:
print(f"\n--- Extracted Table {i+1} ---")
for row in table_data:
print(row)
all_extracted_tables.append(table_data)
return all_extracted_tables
if __name__ == "__main__":
page_html = get_confluence_page_content(PAGE_ID)
if page_html:
extracted_tables = extract_table_data(page_html)
if extracted_tables:
print(f"\nSuccessfully extracted {len(extracted_tables)} table(s) from Confluence page {PAGE_ID}.")
else:
print(f"No tables found on Confluence page {PAGE_ID}.")
else:
print(f"Could not retrieve content for Confluence page {PAGE_ID}.")
直接连接Confluence的后端数据库是一种更复杂且通常不推荐的方法。它主要适用于自托管的Confluence实例,并且在有极端性能需求,且API无法满足时才考虑。
除非您具备深厚的Java/Hibernate背景,并且有极端的性能需求,同时能够接受上述所有风险,否则强烈不建议通过直接连接Confluence后端数据库的方式来提取数据。API通常是更安全、更稳定、更易于维护的选择。
对于从Confluence页面提取结构化数据,尤其是表格数据,强烈推荐使用Confluence REST API。它提供了一个官方、稳定且相对简便的途径,通过Python结合requests和BeautifulSoup等库,可以高效地完成数据提取和解析任务。直接连接Confluence后端数据库虽然技术上可行,但其高昂的复杂性、维护成本和潜在风险使其成为一个在绝大多数情况下都应避免的选项。在开始任何数据提取项目之前,请务必仔细评估您的需求和可用的技术资源,并优先选择最符合“简单、安全、可维护”原则的方案。
以上就是Python从Confluence提取结构化数据:API优先策略的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号