如果你使用的是Django,可以在视图中renderBeautifulSoup的输出:
from django.http import HttpResponse
from django.template import Context, Template
def my_view(request):
# some logic
template = Template(data)
context = Context({}) # you can provide a context if needed
return HttpResponse(template.render(context))
其中data 是BeautifulSoup 的HTML 输出。
另一种选择是使用 Python 的 Basic HTTP server 并提供您拥有的 HTML:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
PORT_NUMBER = 8080
DATA = '<h1>test</h1>' # supposed to come from BeautifulSoup
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(DATA)
return
try:
server = HTTPServer(('', PORT_NUMBER), MyHandler)
print 'Started httpserver on port ', PORT_NUMBER
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
另一种选择是使用selenium,打开about:blank 页面并适当地设置body 标签的innerHTML。换句话说,这会启动浏览器并在正文中提供 HTML 内容:
from selenium import webdriver
driver = webdriver.Firefox() # can be webdriver.Chrome()
driver.get("about:blank")
data = '<h1>test</h1>' # supposed to come from BeautifulSoup
driver.execute_script('document.body.innerHTML = "{html}";'.format(html=data))
屏幕截图(来自 Chrome):
而且,您始终可以选择将BeautifulSoup 的输出保存到 HTML 文件中,然后使用webbrowser 模块(使用file://.. url 格式)打开它。
另见其他选项:
希望对您有所帮助。