4

我一直在使用 lxml 来创建 rss 提要的 xml。但是我在使用标签时遇到了问题,并且无法真正弄清楚如何添加动态数量的元素。鉴于 lxml 似乎只是将函数作为函数的参数,我似乎无法弄清楚如何在不重新制作整个页面的情况下循环获取动态数量的项目。

rss = page = (
      E.rss(
        E.channel(
          E.title("Page Title"),
   E.link(""),
   E.description(""),

            E.item(
                  E.title("Hello!!!!!!!!!!!!!!!!!!!!! "),
                  E.link("htt://"),
                  E.description("this is a"),
            ),
        )
      )
    )
4

3 回答 3

6

Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list: E.channel(*args), where args would be [E.title(...), E.link(...),...]. Similarly, keyword arguments can be passed using dict and two stars (**). See documentation.

于 2010-01-21T00:27:17.967 回答
5

这个 lxml 教程说:


要创建子元素并将它们添加到父元素,可以使用以下append()方法:

>>> root.append( etree.Element("child1") )

然而,这很常见,以至于有一种更短、更有效的方法来做到这一点:SubElement工厂。Element它接受与工厂相同的参数,但还需要父级作为第一个参数:

>>> child2 = etree.SubElement(root, "child2")
>>> child3 = etree.SubElement(root, "child3")

因此,您应该能够创建文档,然后说出channel = rss.find("channel")并使用上述任一方法向channel元素添加更多项目。

于 2010-01-20T23:53:19.633 回答
3
channel = E.channel(E.title("Page Title"), E.link(""),E.description(""))
    for (title, link, description) in container:
        try:
                    mytitle = E.title(title)
                    mylink = E.link(link)
                    mydesc = E.description(description)
            item = E.item(mytitle, mylink, mydesc)
                except ValueError:
                    print repr(title)
                    print repr(link)
                    print repr(description)
                    raise
        channel.append(item)
    top = page = E.top(channel)
于 2010-01-21T17:39:36.997 回答