Open3
Notionのシンプルな表のデータをDataFrameにしたい

Notionのページの内容を取得して"table"
の属性を取得する
import notion_client as nt
import pandas as pd
# Notionの設定
integration_token = "..." # NotionのIntegration Token
page_id = "..." # NotionのページのID
notion_client = nt.Client(auth=integration_token)
# ページの内容
block = notion_client.blocks.children.list(
**{
"block_id": page_id
}
)
# 'table'を持つブロックのID
table_block_indexes = [i for i, x in enumerate(block["results"]) if 'table' in x]
idx = table_block_indexes[0]
table_block_result = block["results"][idx]
table_block_id = table_block_result["id"]
# 'table'を持つブロックの内容
table_block = notion_client.blocks.children.list(
**{
"block_id": table_block_id
}
)

table_block
は各レコードのリストなので、これをパースする
def parse_table_cell(_cell: list) -> str:
"""
セルの情報をパースする
Parameters
----------
_cell
Returns
-------
"""
# 空白の場合は空文字
if len(_cell) == 0:
return ""
# リンクがある場合はリンクを返す
if _cell[0]['href'] is not None:
return _cell[0]['href']
# それ以外はテキストを返す
return _cell[0]['plain_text']
def notion_simple_table_to_dataframe(_table_block: list, header=True) -> pd.DataFrame:
"""
Parameters
----------
_table_block
header
Returns
-------
"""
if header:
header_row = _table_block[0]["table_row"]
columns_name = [parse_table_cell(cell) for cell in header_row["cells"]]
_table_block = _table_block[1:]
else:
columns_name = []
logger.info(f"🎄 [Notion to DataFrame] Table header: {columns_name}")
rows = []
for row in _table_block:
table_row = row["table_row"]
table_cells = table_row["cells"]
# セルの内容をパースする
row_content = [parse_table_cell(cell) for cell in table_cells]
# DataFrame
row_content = pd.DataFrame([row_content],
columns=columns_name if len(columns_name) > 0 else None)
rows.append(row_content)
table = pd.concat(rows, ignore_index=True)
return table

作った関数にtable_block["results"]
を渡せばDataFrameに変換できる
table_df = notion_simple_table_to_dataframe(table_block["results"])