May*_*maz 7 python hyperlink pandas streamlit
我试图在包含 Streamlit 上过滤结果的数据框中显示可单击的超链接。到目前为止,这是我的代码:
import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML
df = pd.read_excel(
io='list.xlsx',
engine= 'openpyxl',
).fillna('')
def make_clickable(link):
# target _blank to open new window
# extract clickable text to display for your link
text = link.split('=')[0]
return f'<a target="_blank" href="{link}">{text}</a>'
# TRAILER is the column with hyperlinks
df['TRAILER'] = df['TRAILER'].apply(make_clickable)
df['TRAILER'] = HTML(display(df.to_html(render_links=True, escape=False), raw=True))
Run Code Online (Sandbox Code Playgroud)
如果我使用:
df['TRAILER'] = df['TRAILER'].apply(make_clickable)
Run Code Online (Sandbox Code Playgroud)
我明白了
<a target="_blank" href="{link}">{text}</a>
Run Code Online (Sandbox Code Playgroud)
显示为字符串而不是超链接。
当我添加:
df['TRAILER'] = HTML(display(df.to_html(render_links=True, escape=False), raw=True))
Run Code Online (Sandbox Code Playgroud)
我得到:
<IPython.core.display.HTML object>
Run Code Online (Sandbox Code Playgroud)
显示为字符串而不是超链接。
这些是我正在使用的版本。该网站的其他组件仅适用于较低版本的 Streamlit,这就是我使用此版本的原因。
streamlit == 0.83 numpy == 1.18 pandas == 1.2 openpyxl ipython == 7.22 python == 3.9
Run Code Online (Sandbox Code Playgroud)

我无法 直接 使用st.markdown or 来显示结果。st.writest.dataframe
您可以使用st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True):
import pandas as pd
import streamlit as st
import openpyxl
import numpy as np
from IPython.core.display import display, HTML
df = pd.read_excel(
io='list.xlsx',
engine= 'openpyxl',
).fillna('')
def make_clickable(link):
# target _blank to open new window
# extract clickable text to display for your link
text = link.split('=')[0]
return f'<a target="_blank" href="{link}">{text}</a>'
# TRAILER is the column with hyperlinks
df['TRAILER'] = df['TRAILER'].apply(make_clickable)
st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True)
Run Code Online (Sandbox Code Playgroud)
在一个工作示例中:
import pandas as pd
import streamlit as st
link1 = "/sf/ask/5014916651/"
link2 = "/sf/ask/5021235621/"
df = pd.DataFrame(
{
"url": [
f'<a target="_blank" href="{link1}">Hyperlink in Streamlit dataframe</a>',
f'<a target="_blank" href="{link2}">How to plot comparison in Streamlit dynamically with multiselect?</a>'
],
"label": ["question", "question"]
}
)
st.write(df.to_html(escape=False, index=False), unsafe_allow_html=True)
Run Code Online (Sandbox Code Playgroud)
它给: