You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取Streamlit网页的完整HTML输出?

解决Streamlit页面导出PDF/获取完整HTML的问题

原代码的核心问题

你当前的代码中,st.write("asdasd")的返回值是None,所以变量a实际为空,导致导出的PDF没有内容。另外Streamlit本身没有提供直接获取页面完整HTML的API——因为它的UI是前端动态渲染的,后端无法通过单一变量直接捕获所有页面元素。

可行解决方案

方案一:统一管理展示与导出的内容

如果只需要导出自己添加的业务内容,不需要Streamlit自带的UI组件(侧边栏、按钮等),可以提前把要展示的内容存在变量中,既用来在页面显示,也用来生成PDF,保证内容一致性:

from fpdf import FPDF
import base64
import streamlit as st

# 统一存储要展示和导出的内容
content = "asdasd"
st.write(content)

export_as_pdf = st.button("Export Report")

def create_download_link(val, filename):
    b64 = base64.b64encode(val)
    return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}.pdf">Download file</a>'

if export_as_pdf:
    pdf = FPDF()
    pdf.add_page()
    pdf.cell(0, 5, content)
    
    html = create_download_link(pdf.output(dest="S").encode("latin-1"), "test")
    st.markdown(html, unsafe_allow_html=True)

方案二:抓取完整页面HTML转PDF

如果需要导出包含Streamlit所有UI元素的完整页面,可以用Selenium模拟浏览器访问,抓取页面的完整HTML后再转换为PDF:

import streamlit as st
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import base64
import pdfkit

# 配置Selenium无头浏览器模式
chrome_options = Options()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--disable-gpu")

export_as_pdf = st.button("Export Full Page as PDF")

def create_download_link(val, filename):
    b64 = base64.b64encode(val)
    return f'<a href="data:application/octet-stream;base64,{b64.decode()}" download="{filename}.pdf">Download file</a>'

if export_as_pdf:
    # 替换为你的Streamlit应用运行地址
    app_url = "http://localhost:8501"
    
    # 启动浏览器获取页面源码
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(app_url)
    full_page_html = driver.page_source
    driver.quit()
    
    # 将HTML转为PDF(需提前安装pdfkit和wkhtmltopdf)
    pdf_bytes = pdfkit.from_string(full_page_html, False)
    
    # 生成下载链接
    html = create_download_link(pdf_bytes, "full_page_report")
    st.markdown(html, unsafe_allow_html=True)
方案二注意事项
  • 需安装依赖:pip install selenium pdfkit
  • 需安装wkhtmltopdf:Windows从官网下载安装,Linux执行sudo apt-get install wkhtmltopdf,macOS用brew install wkhtmltopdf
  • 运行Streamlit应用时,确保Selenium能访问到应用URL(本地运行默认是http://localhost:8501)

内容的提问来源于stack exchange,提问作者leo dinaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:15:31