Search code examples
google-colaboratory

How to retrive the notebook contents or the url of a particular cell in Google colab


Is there a way to get or compute the URL to a cell in Colab? I know you can click on a link button to get the url, or click on the TOC and get the #scrollTo=J1nFJPC9V1-X part of the URL, but I want a way to generate this.

The use case is I search colabs for headlines, and I want to generate a link that opens a colab to that heading. Suppose I know the id for a colab, and I know it has a heading called "Printing arrays". I want to generate a full link that opens it at that cell.

Is it possible to compute the scrollTo part, or retrieve it somehow?


Solution

  • Here's an example snippet that will find the cell ID with particular contents:

    from google.colab import _message
    
    # Load the notebook JSON.
    nb = _message.blocking_request('get_ipynb')
    
    # Search for the markdown cell with the particular contents.
    for cell in nb['ipynb']['cells']:
      if (cell['cell_type'] == 'markdown' and 
          '\n'.join(cell['source']).find('## Printing arrays') >= 0):
        print (f'Cell ID for header is #{cell["metadata"]["id"]}')
    

    Here's a complete example notebook: https://colab.research.google.com/drive/11jOuhB7wzm1d2P85mrmhBWycogJ_9F0q