直接从 Python 在浏览器中启动 HTML 代码(由 BeautifulSoup 生成) [英] Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python
问题描述
我使用 BeautifulSoup for Python 3.3 成功地从网页中提取所需信息.我还使用 BeautifulSoup 生成新的 HTML 代码来显示此信息.目前,我的 Python 程序会打印出 HTML 代码,然后我必须将其复制、粘贴并另存为 HTML 文件,然后从那里我可以在浏览器中对其进行测试.
I have used BeautifulSoup for Python 3.3 to successfully pull desired info from a web page. I have also used BeautifulSoup to generate new HTML code to display this info. Currently, my Python program prints out the HTML code, which I then have to copy, paste, and save as an HTML file, then from there, I can test it in a browser.
所以我的问题是,Python 中是否有一种方法可以在 Web 浏览器中启动由 BeautifulSoup 生成的 HTML 代码,这样我就不必通过我现在使用的复制和粘贴方法?
So my question is this, is there a way in Python to launch the HTML code generated by BeautifulSoup in a web browser so that I don't have to go through the copy and paste method I use now?
推荐答案
使用 webbrowser.open
:
import os
import webbrowser
html = '<html> ... generated html string ...</html>'
path = os.path.abspath('temp.html')
url = 'file://' + path
with open(path, 'w') as f:
f.write(html)
webbrowser.open(url)
替代使用 NamedTemporaryFile
(使文件最终被操作系统删除):
Alternative using NamedTemporaryFile
(to make the file eventually deleted by OS):
import tempfile
import webbrowser
html = '<html> ... generated html string ...</html>'
with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
url = 'file://' + f.name
f.write(html)
webbrowser.open(url)
这篇关于直接从 Python 在浏览器中启动 HTML 代码(由 BeautifulSoup 生成)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!