使用 BeautifulSoup 创建 XML 文档 [英] Creating an XML document with BeautifulSoup

查看:16
本文介绍了使用 BeautifulSoup 创建 XML 文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看过的所有关于 BeautifulSoup 的示例和教程中,传递了一个 HTML/XML 文档并返回一个汤对象,然后可以使用它来修改文档.但是,如何使用 BeautifulSoup 从头开始​​创建 HTML/XML 文档?换句话说,我想将数据放入 XML 文件中,但 XML 文件尚不存在,我想从头开始构建它.我该怎么办?

In all the examples and tutorials I have seen of BeautifulSoup, an HTML/XML document is passed and a soup object is returned which can then be used to modify the document. However, how can I use BeautifulSoup to create a HTML/XML document from scratch? In other words, I have data that I would like to put in an XML file, but the XML file does not exist yet and I would like to build it from scratch. How can I go about it?

推荐答案

只需创建一个空的 BeautifulSoup() 对象:

Just create an empty BeautifulSoup() object:

soup = BeautifulSoup()

并开始添加元素:

soup.append(soup.new_tag("a", href="http://www.example.com"))

对于 XML,您可以使用 xml 树构建器从 XML 标头开始:

For XML you could start out with a XML header by using the xml tree builder:

soup = BeautifulSoup(features='xml')

这需要先安装lxml.这会在 BeautifulSoup 对象上设置 .is_xml 标志(也可以手动设置).

This requires lxml to be installed first. This sets the .is_xml flag on the BeautifulSoup object (which can also be set manually).

这篇关于使用 BeautifulSoup 创建 XML 文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆