Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python

后端 未结 3 666
情深已故
情深已故 2020-12-09 16:16

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. Cu

3条回答
  •  长情又很酷
    2020-12-09 16:29

    Using webbrowser.open:

    import os
    import webbrowser
    
    html = ' ...  generated html string ...'
    path = os.path.abspath('temp.html')
    url = 'file://' + path
    
    with open(path, 'w') as f:
        f.write(html)
    webbrowser.open(url)
    

    Alternative using NamedTemporaryFile (to make the file eventually deleted by OS):

    import tempfile
    import webbrowser
    
    html = ' ...  generated html string ...'
    
    with tempfile.NamedTemporaryFile('w', delete=False, suffix='.html') as f:
        url = 'file://' + f.name
        f.write(html)
    webbrowser.open(url)
    

提交回复
热议问题