使用webbrowser生成并打开HTML字符串,无需访问光盘

2024-06-26 14:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的代码中创建一个HTML文件,并用它在chrome中打开一个新选项卡

这是我的密码。它的工作原理是:

with open('mysite.html','w') as f:
    f.write('<html>')
    f.write('<head>')
    f.write('<title>Table of contents</title>')
    f.write('</head>')
    f.write('<body>')
    # myhtmltable is a pandas dataframe containing only text 
    f.write(myhtmltable)
    f.write('</body>')
    f.write('</html>')

chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

webbrowser.get(chrome_path).open('mysite.html')

如您所见,我在.py所在的本地文件夹中创建了一个文件

是否可能在运行中创建HTML文件,而不必访问光盘,即保存文件并使用webbrowser读取

因此,如果我有类似于:

myhtml = '<html><head><title>Table of contents</title></head><body>this is the body</body></html>'

我可以直接发送到chrome标签吗

这里有两种解决方案,但都是创建本地文件: Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python


Tags: 文件oftitleishtmlcontentstablebody