代码之家  ›  专栏  ›  技术社区  ›  May Mammaz

Streamlight数据帧中的超链接

  •  0
  • May Mammaz  · 技术社区  · 3 年前

    我试图在数据框内显示一个可点击的超链接,其中包含Streamlight上的过滤结果。这是我目前的代码:

    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))
    

    如果我使用:

    df['TRAILER'] = df['TRAILER'].apply(make_clickable)
    

    我明白了

    <a target="_blank" href="{link}">{text}</a>
    

    显示为字符串,但不是超链接。

    当我加上:

    df['TRAILER'] = HTML(display(df.to_html(render_links=True, escape=False), raw=True))
    

    我得到:

    <IPython.core.display.HTML object>
    

    显示为字符串,但不是超链接。

    这些是我正在使用的版本。该网站的其他组件只能使用较低版本的Streamlight,这就是我使用此版本的原因。

    streamlit == 0.83 numpy == 1.18 pandas == 1.2 openpyxl ipython == 7.22 python == 3.9
    

    site screenshot

    我不能用 st.markdown st.write 正如我所用 st.dataframe 以显示结果。

    0 回复  |  直到 3 年前
        1
  •  0
  •   vvvvv lexa-b    3 年前

    你可以用 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)
    

    例如:

    import pandas as pd
    import streamlit as st
    
    link1 = "https://stackoverflow.com/questions/71641666/hyperlink-in-streamlit-dataframe"
    link2 = "https://stackoverflow.com/questions/71731937/how-to-plot-comparison-in-streamlit-dynamically-with-multiselect"
    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)
    

    它给出:

    Hyperlinks to SO questions (dataframe)