program story

파이썬에서 HTML 문서 생성

inputbox 2020. 12. 25. 09:43
반응형

파이썬에서 HTML 문서 생성


파이썬에서 HTML 문서를 생성하는 가장 우아한 방법은 무엇입니까? 현재 모든 태그를 거대한 문자열에 수동으로 추가하고 파일에 씁니다. 이 작업을 수행하는 더 우아한 방법이 있습니까?


나는 찾을 yattag가 이 일의 가장 우아한 방법이 될 수 있습니다.

from yattag import Doc

doc, tag, text = Doc().tagtext()

with tag('html'):
    with tag('body'):
        with tag('p', id = 'main'):
            text('some text')
        with tag('a', href='/my-url'):
            text('some link')

result = doc.getvalue()

태그를 닫을 필요가 없다는 추가 이점과 함께 html처럼 읽습니다.


파이썬에 사용할 수있는 많은 템플릿 언어 중 하나를 사용하는 것이 좋습니다. 예를 들어 Django에 내장 된 언어 (템플릿 엔진을 사용하기 위해 나머지 Django를 사용할 필요가 없습니다)-Google 쿼리는 다른 많은 대안을 제공해야합니다. 템플릿 구현.

템플릿 라이브러리를 배우는 것이 많은면에서 도움이된다는 것을 알게되었습니다. 이메일, HTML 페이지, 텍스트 파일 등을 생성해야 할 때마다 템플릿을 작성하고 템플릿 라이브러리와 함께로드 한 다음 템플릿 코드가 완제품.

시작하는 데 도움이되는 간단한 코드는 다음과 같습니다.

#!/usr/bin/env python

from django.template import Template, Context
from django.conf import settings
settings.configure() # We have to do this to use django templates standalone - see
# http://stackoverflow.com/questions/98135/how-do-i-use-django-templates-without-the-rest-of-django

# Our template. Could just as easily be stored in a separate file
template = """
<html>
<head>
<title>Template {{ title }}</title>
</head>
<body>
Body with {{ mystring }}.
</body>
</html>
"""

t = Template(template)
c = Context({"title": "title from code",
             "mystring":"string from code"})
print t.render(c)

디스크에 템플릿이있는 경우 훨씬 더 간단합니다 . 미리 정의 된 검색 경로 목록에서 디스크에서 템플릿을로드하고, 사전의 데이터를 채우고, 문자열로 렌더링 할 수있는 django 1.7 용 render_to_string 함수를 확인하십시오 . (django 1.8에서 제거됨 , 비슷한 작업 Engine.from_string 참조 )


HTML 문서를 작성하는 경우 다른 사람들이 제안한대로 템플릿 시스템 (예 : jinja2 )을 사용하는 것이 좋습니다 . (아마도 템플릿 중 하나에 대한 입력으로) 낮은 수준의 html 비트 생성이 필요한 경우 xml.etree 패키지는 표준 Python 패키지이며 계산서에 잘 맞을 수 있습니다.

import sys
from xml.etree import ElementTree as ET

html = ET.Element('html')
body = ET.Element('body')
html.append(body)
div = ET.Element('div', attrib={'class': 'foo'})
body.append(div)
span = ET.Element('span', attrib={'class': 'bar'})
div.append(span)
span.text = "Hello World"

if sys.version_info < (3, 0, 0):
  # python 2
  ET.ElementTree(html).write(sys.stdout, encoding='utf-8',
                             method='html')
else:
  # python 3
  ET.ElementTree(html).write(sys.stdout, encoding='unicode',
                             method='html')

다음을 인쇄합니다.

<html><body><div class="foo"><span class="bar">Hello World</span></div></body></html>

이렇게하려면 xml.dom을 사용하는 것이 좋습니다.

http://docs.python.org/library/xml.dom.html

이 매뉴얼 페이지를 읽으면 XML (따라서 XHTML)을 구축하는 방법이 있습니다. 자식 노드, 문서 유형 추가, 속성 추가, 텍스트 노드 생성을 포함한 모든 XML 작업을 훨씬 쉽게 만듭니다. 이것은 HTML을 작성하기 위해 수행 할 대부분의 작업에 도움이 될 것입니다.

또한 기존 xml 문서를 분석하고 처리하는 데 매우 유용합니다.

Hope this helps

P.S

Here is a tutorial that should help you with applying the syntax

http://www.postneo.com/projects/pyxml/


I am using the code snippet known as throw_out_your_templates for some of my own projects:

https://github.com/tavisrudd/throw_out_your_templates

https://bitbucket.org/tavisrudd/throw-out-your-templates/src

Unfortunately, there is no pypi package for it and it's not part of any distribution as this is only meant as a proof-of-concept. I was also not able to find somebody who took the code and started maintaining it as an actual project. Nevertheless, I think it is worth a try even if it means that you have to ship your own copy of throw_out_your_templates.py with your code.

Similar to the suggestion to use yattag by John Smith Optional, this module does not require you to learn any templating language and also makes sure that you never forget to close tags or quote special characters. Everything stays written in Python. Here is an example of how to use it:

html(lang='en')[
  head[title['An example'], meta(charset='UTF-8')],
  body(onload='func_with_esc_args(1, "bar")')[
      div['Escaped chars: ', '< ', u'>', '&'],
      script(type='text/javascript')[
           'var lt_not_escaped = (1 < 2);',
           '\nvar escaped_cdata_close = "]]>";',
           '\nvar unescaped_ampersand = "&";'
          ],
      Comment('''
      not escaped "< & >"
      escaped: "-->"
      '''),
      div['some encoded bytes and the equivalent unicode:',
          '你好', unicode('你好', 'utf-8')],
      safe_unicode('<b>My surrounding b tags are not escaped</b>'),
      ]
  ]

Yes, you are looking for file .writelines

A sequence is generally a list or array. So put all your lines into a list or array. And toss them to the function below.

Make sure to remove any new line constants from your strings just to be safe

Python Documentation ( search for file.writelines )

file.writelines(sequence) Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.)

ReferenceURL : https://stackoverflow.com/questions/6748559/generating-html-documents-in-python

반응형