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

后端 未结 3 655
情深已故
情深已故 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 = '<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)
    

    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)
    
    0 讨论(0)
  • 2020-12-09 16:29

    (this grew enough I figured I should split it off as a separate answer:)

    As @reptilicus points out, you can use the built-in http.server module as follows:

    1. Create a web file directory and save your .html file in it.

    2. Open a command-line window and do

      cd /my/web/directory
      python -m http.server 8000
      
    3. Point your browser at http://127.0.0.1:8000

    This only works for static files; it will not run your script and return the results (as Flask does).

    0 讨论(0)
  • 2020-12-09 16:30

    Use Flask to turn your code into a local web application:

    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def scrape_and_reformat():
        # call your scraping code here
        return '<html><body> ... generated html string ... </body></html>'
    
    if __name__ == '__main__':
        app.run()
    

    Run the script, and point your browser at http://127.0.0.1:5000/.

    0 讨论(0)
提交回复
热议问题