自定义Python主导标签元素

时间:2019-04-27 20:29:05

标签: python html webp dominate

对于support both a JPEG and WEBP compressed image,我想在网页中包含以下HTML代码:

<picture>
  <source srcset="img/awesomeWebPImage.webp" type="image/webp">
  <source srcset="img/creakyOldJPEG.jpg" type="image/jpeg"> 
  <img src="img/creakyOldJPEG.jpg" alt="Alt Text!">
</picture>

我一直在使用Python Dominate,它通常对我来说效果很好。 但是我认为“图片”和“源”标签不受Dominate支持。 我可以将HTML添加为raw()Dominate标签,但是想知道是否有一种方法可以使Dominate识别这些标签。

p = picture()
with p:
    source(srcset=image.split('.')[0]+'.webp', type="image/webp")
    source(srcset=image, type="image/jpeg")
    img(src=image, alt=imagealt)

我看到这种错误:

p = picture()
NameError: global name 'picture' is not defined

2 个答案:

答案 0 :(得分:2)

您可以通过继承dominate.tags.html_tag

来创建图片类
from dominate.tags import html_tag

class picture(html_tag):
    pass

现在可以将其用作任何预定义标签。

答案 1 :(得分:0)

Dominate用于生成HTML(5)文档。

元素列表在tags.py文件中定义,请参见GitHub中的存储库:https://github.com/Knio/dominate/blob/master/dominate/tags.py

但是,picture不是标准标记。

您可能会看一下包含ElementMaker的lxml库,该库类似于Dominate,可以轻松地构建XML树。参见E-Factory

例如:

>>> from lxml.builder import E

>>> def CLASS(*args): # class is a reserved word in Python
...     return {"class":' '.join(args)}

>>> html = page = (
...   E.html(       # create an Element called "html"
...     E.head(
...       E.title("This is a sample document")
...     ),
...     E.body(
...       E.h1("Hello!", CLASS("title")),
...       E.p("This is a paragraph with ", E.b("bold"), " text in it!"),
...       E.p("This is another paragraph, with a", "\n      ",
...         E.a("link", href="http://www.python.org"), "."),
...       E.p("Here are some reserved characters: <spam&egg>."),
...       etree.XML("<p>And finally an embedded XHTML fragment.</p>"),
...     )
...   )
... )

>>> print(etree.tostring(page, pretty_print=True))
<html>
  <head>
    <title>This is a sample document</title>
  </head>
  <body>
    <h1 class="title">Hello!</h1>
    <p>This is a paragraph with <b>bold</b> text in it!</p>
    <p>This is another paragraph, with a
      <a href="http://www.python.org">link</a>.</p>
    <p>Here are some reserved characters: &lt;spam&amp;egg&gt;.</p>
    <p>And finally an embedded XHTML fragment.</p>
  </body>
</html>