lxml 和循环在 python 中创建 xml rss
我一直在使用 lxml 创建 rss feed 的 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"),
),
)
)
)
I have been using lxml to create the xml of rss feed. But I am having trouble with the tags and cant really figure out how to to add a dynamic number of elements. Given that lxml seems to just have functions as parameters of functions, I cant seem to figure out how to loop for a dynamic number of items without remaking the entire page.
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"),
),
)
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
杰森已经回答了你的问题;但是 - 仅供参考 - 您可以将任意数量的函数参数作为列表动态传递:
E.channel(*args)
,其中args
将是[E.channel(*args)]。标题(
...),E.link(
...),
...]
。同样,关键字参数可以使用 dict 和两个星号 (**
) 来传递。请参阅文档。Jason has answered your question; but – just FYI – you can pass any number of function arguments dynamically as a list:
E.channel(*args)
, whereargs
would be[E.title(
...), E.link(
...),
...]
. Similarly, keyword arguments can be passed using dict and two stars (**
). See documentation.这个 lxml 教程 说:
创建子元素并将它们添加到父元素元素,您可以使用
append()
方法:但是,这种情况很常见,因此有一种更短且更有效的方法来执行此操作:
SubElement
工厂。它接受与Element
工厂相同的参数,但还需要父级作为第一个参数:因此您应该能够创建文档,然后说
channel = rss.find("channel" )
并使用上述任一方法向channel
元素添加更多项目。This lxml tutorial says:
To create child elements and add them to a parent element, you can use the
append()
method:However, this is so common that there is a shorter and much more efficient way to do this: the
SubElement
factory. It accepts the same arguments as theElement
factory, but additionally requires the parent as first argument:So you should be able to create the document, then say
channel = rss.find("channel")
and use either of the above methods to add more items to thechannel
element.