美丽汤的输出可以发送到浏览器吗?
我最近刚接触Python,之前大部分时间都是在用PHP。PHP在处理HTML时有个很方便的地方,就是它的echo语句可以直接把HTML输出到浏览器。这让我们可以使用浏览器自带的开发者工具,比如firebug。那么,有没有办法把Python/Django的输出从命令行转到浏览器,特别是在使用像Beautiful Soup这样的工具时?理想情况下,每次运行代码时都能打开一个新的浏览器标签页。
1 个回答
6
如果你在使用Django框架,你可以在视图中将BeautifulSoup
的输出进行render
处理:
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的基本HTTP服务器来提供你已有的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格式)。
你还可以查看其他选项:
希望这些对你有帮助。