自定义Python支配标记元素

问题描述 投票:0回答:1

对于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不支持Picture和Source标签。我可以将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
python html webp dominate
1个回答
0
投票

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

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

但是,picture不是标准标签。

您可以查看包含类似于Dominate的ElementMaker的lxml库,以便轻松构建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>
© www.soinside.com 2019 - 2024. All rights reserved.