Display URLs in dataframe column as a clickable hyperlink

One of the columns of a dataframe I want to display in my streamlit app contains URLs and I would like it to displayed as a clickable hyperlink.

How can I do this? I tried modifying the column or using a style to wrap the url with html tags but it does not render correctly.


You can do df.to_html(escape=False) and then your dataframe should render that column containing HTML href= code.

You can do:

st.write(your_dataframe.to_html(escape=False, index=False), unsafe_allow_html=True)

But what gets rendered is just plain HTML, not the nice looking streamlit rendered dataframe. So perhaps not what you want. Until the streamlit team allows execution of HTML within the streamlit version of dataframe, not sure what else can be done. There is a separate post concerning allowing HTML code execution.

1 Like

I need to display URLs as a clickable hyperlink also. Can it be accomplished using pandas Styler?

Thanks, all. I got this to work now. Here’s what I am doing:

def make_clickable(link):
    # target _blank to open new window
    # extract clickable text to display for your link
    text = link.split('=')[1]
    return f'<a target="_blank" href="{link}">{text}</a>'

# link is the column with hyperlinks
df['link'] = df['link'].apply(make_clickable)
df = df.to_html(escape=False)
st.write(df, unsafe_allow_html=True)

How many characters is your link/markup? I have the problem that streamlit or pandas is cutting off the text at a certain character (followed by an ellipsis ...) which then breaks the HTML.


Ah got it working, if anyone has the same issue then you need to change pandas` display options:

pd.set_option('display.max_colwidth', -1)

1 Like

Hmm I was not able to get this work for me within streamlit. Works outside of using streamlit.

EDIT: Per this discussion your suggestion does not work. However, the current workaround is to use st.table() which perhaps is what you did, but forgot to include that info, which also has some drawbacks too.

1 Like

If by “outside of streamlit” you mean just a table rather than the scrollable tables then yes, you are right. Ideally I would like to use the scrollable table and HTML (all I really need is the link), but for now I’m happy to settle with having just a static table w/ the links.

As for the implementation, I used a combination of the suggestions here:

# pandas display options
pd.set_option('display.max_colwidth', -1)

def add_stream_url(track_ids):
	return [f'https://open.spotify.com/track/{t}' for t in track_ids]

def make_clickable(url, text):
    return f'<a target="_blank" href="{url}">{text}</a>'

# show data
if st.checkbox('Include Preview URLs'):
	df['preview'] = add_stream_url(df.track_id)
	df['preview'] = df['preview'].apply(make_clickable, args = ('Listen',))
	st.write(df.to_html(escape = False), unsafe_allow_html = True)