谷歌分析在Streamlit应用程序上无法正常工作

huangapple go评论61阅读模式
英文:

Google Analytics is not working on Streamlit Application

问题

# 添加Google Analytics代码到头部
ga_code = """
<!-- 谷歌标签 (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxx"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());

    gtag('config', 'G-xxxxxx');
</script>
"""
st.markdown(ga_code, unsafe_allow_html=True)
英文:

I have built a web application using streamlit and hosted it on the Google Cloud Platform (App Engine). The URL is something like https://xxx-11111.uc.r.appspot.com/ which is given for the Stream URL.

I enabled Google Analytics 2 days back but apparently, it is not set up correctly.

It was given that I need to add in the head tag.

This is the code where I added the Google Analytics tag...

What is wrong??

def page_header():
    st.set_page_config(page_title="xx", page_icon="images/logo.png")
    header = st.container()
    with header:
        # Add banner image
        logo = Image.open("images/logo.png")
        st.image(logo, width=300)

        # Add Google Analytics code to the header
        ga_code = """
        <!-- Google tag (gtag.js) -->
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxx"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());

            gtag('config', 'G-xxxxxx');
        </script>
        """
        st.markdown(ga_code, unsafe_allow_html=True)


# Define the main function to run the app
def main():

    # Render the page header
    page_header()

    .....

if __name__ == "__main__":
    main()

答案1

得分: 1

One way to implement Google Analytics into your GAE Streamlit app would be to add the GA global site tag JS code to the default /site-packages/streamlit/static/index.html file.

注意:在运行 Streamlit 服务器之前,应运行此脚本。

from bs4 import BeautifulSoup
import shutil
import pathlib
import logging
import streamlit as st

def add_analytics_tag():
    # 将 G-XXXXXXXXXX 替换为您的网络应用的 ID
    
    analytics_js = """
    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-XXXXXXXXXX');
    </script>
    <div id="G-XXXXXXXXXX"></div>
    """
    analytics_id = "G-XXXXXXXXXX"
    
    # 识别 streamlit 的 HTML 路径
    index_path = pathlib.Path(st.__file__).parent / "static" / "index.html"
    logging.info(f'正在编辑 {index_path}')
    soup = BeautifulSoup(index_path.read_text(), features="html.parser")
    if not soup.find(id=analytics_id): # 如果在 HTML 文件中找不到该 ID
        bck_index = index_path.with_suffix('.bck')
        if bck_index.exists():
            shutil.copy(bck_index, index_path)  # 备份恢复
        else:
            shutil.copy(index_path, bck_index)  # 保存备份
        html = str(soup)
        new_html = html.replace('<head>', '<head>\n' + analytics_js) 
        index_path.write_text(new_html) # 在头部插入分析标签
英文:

One way to implement Google Analytics into your GAE Streamlit app would be to add the GA global site tag JS code to the default /site-packages/streamlit/static/index.html file

NOTE: This script should be run prior to running the streamlit server

from bs4 import BeautifulSoup
import shutil
import pathlib
import logging
import streamlit as st


def add_analytics_tag():
    # replace G-XXXXXXXXXX to your web app&#39;s ID
    
    analytics_js = &quot;&quot;&quot;
    &lt;!-- Global site tag (gtag.js) - Google Analytics --&gt;
    &lt;script async src=&quot;https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX&quot;&gt;&lt;/script&gt;
    &lt;script&gt;
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag(&#39;js&#39;, new Date());
        gtag(&#39;config&#39;, &#39;G-XXXXXXXXXX&#39;);
    &lt;/script&gt;
    &lt;div id=&quot;G-XXXXXXXXXX&quot;&gt;&lt;/div&gt;
    &quot;&quot;&quot;
    analytics_id = &quot;G-XXXXXXXXXX&quot;

    
    # Identify html path of streamlit
    index_path = pathlib.Path(st.__file__).parent / &quot;static&quot; / &quot;index.html&quot;
    logging.info(f&#39;editing {index_path}&#39;)
    soup = BeautifulSoup(index_path.read_text(), features=&quot;html.parser&quot;)
    if not soup.find(id=analytics_id): # if id not found within html file
        bck_index = index_path.with_suffix(&#39;.bck&#39;)
        if bck_index.exists():
            shutil.copy(bck_index, index_path)  # backup recovery
        else:
            shutil.copy(index_path, bck_index)  # save backup
        html = str(soup)
        new_html = html.replace(&#39;&lt;head&gt;&#39;, &#39;&lt;head&gt;\n&#39; + analytics_js) 
        index_path.write_text(new_html) # insert analytics tag at top of head

huangapple
  • 本文由 发表于 2023年4月17日 18:54:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034389.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定