标签:html python beautifulsoup browser html-parsing
我最近刚刚介绍了python的新手,但我拥有大部分的php经验.使用HTML时(不出意外),php支持的一件事是echo语句将HTML输出到浏览器.这使您可以使用内置的浏览器开发工具,如firebug.有没有办法在使用美丽的汤等工具时将输出python / django从命令行重新路由到浏览器?理想情况下,每次运行代码都会打开一个新的浏览器选项卡.
解决方法:
如果是你正在使用的Django,你可以在视图中render输出BeautifulSoup:
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格式).
另见其他选项:
> Launch HTML code in browser (that is generated by BeautifulSoup) straight from Python
希望有所帮助.
标签:html,python,beautifulsoup,browser,html-parsing 来源: https://codeday.me/bug/20190830/1768648.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。