Created
June 12, 2020 09:57
-
-
Save ClementC/9d1a6843e8a7268fc77b34e927dc78c9 to your computer and use it in GitHub Desktop.
A small snippet to search and replace in all of your Notion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import notion | |
from notion.client import NotionClient | |
from collections import Counter | |
from tqdm import tqdm | |
from pprint import pprint | |
from getpass import getpass | |
search_for = "value_to_be_searched" | |
replace_with = "new_value" | |
# Obtain the `token_v2` value by inspecting your browser cookies on a logged-in session on Notion.so | |
client = NotionClient(token_v2=getpass("Token?")) | |
# Search all blocks containing the domain we want to change | |
search_results = client.search_blocks(search_for, limit=1000) | |
# Pretty print the bearkdown by block types | |
pprint(Counter([type(b) for b in search_results])) | |
# Define separate block types according to where we should look for text | |
# (this was established after manual examination) | |
map_block_types_by_attribute = { | |
"title": [notion.block.TextBlock, notion.collection.CollectionRowBlock, notion.block.BulletedListBlock, | |
notion.block.SubheaderBlock, notion.block.CalloutBlock, notion.block.NumberedListBlock, | |
notion.block.SubsubheaderBlock, notion.block.CodeBlock, notion.block.TodoBlock], | |
"caption": [notion.block.ImageBlock, notion.block.BookmarkBlock] | |
} | |
block_type_to_attribute = {block_type: attr | |
for attr, block_types_list in map_block_types_by_attribute.items() | |
for block_type in block_types_list} | |
# Replace the occurrences we want | |
for block in tqdm(search_results): | |
block_type = type(block) | |
attr = block_type_to_attribute.get(block_type) | |
if attr is None: | |
continue | |
block.__setattr__(attr, | |
block.__getattribute__(attr).replace(search_for, | |
replace_with)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment