Skip to content

Instantly share code, notes, and snippets.

@sajalshres
Last active April 22, 2024 03:56
Show Gist options
  • Save sajalshres/b016fb0dbc9a470b85cb0f9da80b76eb to your computer and use it in GitHub Desktop.
Save sajalshres/b016fb0dbc9a470b85cb0f9da80b76eb to your computer and use it in GitHub Desktop.
Update Atlassian Confluence Page with Table format
CONFLUENCE_TOKEN=<TOKEN>
CONFLUENCE_INSTANCE=<confluence.server.com>
import os
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv
# load environment variables from .env file
load_dotenv(override=True)
# Set requests session
session = requests.Session()
session.headers = {
"Authorization": f"Bearer {os.getenv('CONFLUENCE_TOKEN')}",
"Content-Type": "application/json",
}
# Set URL
base_url = f"https://{os.getenv('CONFLUENCE_INSTANCE')}/rest/api"
# Set Page ID
page_id = "98368"
data = session.get(f"{base_url}/content/{page_id}?expand=body.view,version").json()
html_content = data["body"]["view"]["value"]
soup = BeautifulSoup(html_content, "html.parser")
# Debug: Print soup to verify correct parsing
print(soup.prettify())
# Locating the table more reliably
table = soup.find('table', class_='confluenceTable')
if table is None:
raise ValueError("The expected table was not found in the HTML content.")
# Adding a new row to the table
new_row = soup.new_tag("tr")
# New data
cells = ["new-pipeline", "2.0.0"]
for cell in cells:
td = soup.new_tag('td', attrs={'class': 'confluenceTd'})
td.string = cell
new_row.append(td)
if table.tbody:
table.tbody.append(new_row)
else:
tbody = soup.new_tag('tbody')
tbody.append(new_row)
table.append(tbody)
# Converting modified HTML back to string
updated_html_content = str(soup)
# Print modified HTML to verify the changes
print(soup.prettify())
# Preparing the JSON payload for the Confluence API
current_version = data["version"]["number"]
update_payload = {
"id": page_id,
"type": "page",
"title": data["title"],
"body": {"storage": {"value": updated_html_content, "representation": "storage"}},
"version": {
"number": current_version + 1 # Increment the existing version number by 1
},
}
response = session.put(f"{base_url}/content/{page_id}", json=update_payload).json()
# Print the response from the server to check if the update was successful
print(response)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment