可美丽的汤输出发送到浏览器? [英] Can beautiful soup output be sent to browser?
问题描述
我已经最近推出的pretty新的蟒蛇,但有我的大部分用PHP的经验。在PHP与HTML工作时已经为它去一件事(这并不奇怪)是echo语句输出HTML浏览器。这可让您使用内置的浏览器开发工具,如萤火虫。有没有一种方法使用工具时重新路由命令行的浏览器输出的Python / Django的美丽汤?理想情况下,code的每次运行将打开一个新的浏览器选项卡。
I'm pretty new to python having been introduced recently , but having most of my experience with php. One thing that php has going for it when working with HTML (not surprisingly) is that the echo statement outputs HTML to the browser. This lets you use the built in browser dev tools such as firebug. Is there a way to reroute output python/django from the command line to the browser when using tools such as beautiful soup? Ideally each run of the code would open a new browser tab.
推荐答案
如果它是你使用,你可以的渲染 BeautifulSoup
中的观点:
If it is Django you are using, you can render the output of BeautifulSoup
in the view:
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))
其中,数据
是输出HTML BeautifulSoup
。
另一种选择是使用Python的基本HTTP服务器并服务于HTML您有:
Another option would be to use Python's Basic HTTP server and serve the HTML you have:
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()
另一种选择是使用 硒
,打开关于:空白
页,并设置体
标签的的innerHTML
得体。换句话说,这将启动一个浏览器与在体内提供HTML内容:
Another option would be to use selenium
, open about:blank
page and set the body
tag's innerHTML
appropriately. In other words, this would fire up a browser with the provided HTML content in the body:
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浏览器):
Screenshot (from Chrome):
和,你总是有一个选项 BeautifulSoup
的输出保存到一个HTML文件和使用的 web浏览器
模块(使用文件:// ..
URL格式)。
And, you always have an option to save the BeautifulSoup
's output into an HTML file and open it using webbrowser
module (using file://..
url format).
另请参阅其他选项:
- Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python
希望有所帮助。
这篇关于可美丽的汤输出发送到浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!