我有一个简单的HTML文件我想转换。根据标记的类别,我需要修改内容:
<HTML>
<HEAD>
<TITLE>Eine einfache HTML-Datei</TITLE>
<meta name="description" content="A simple HTML page for BS4">
<meta name="author" content="Uwe Ziegenhagen">
<meta charset="UTF-8">
</HEAD>
<BODY>
<H1>Hallo Welt</H1>
<p>Ein kurzer Absatz mit ein wenig Text, der relativ nichtssagend ist.</p>
<H1>Nochmal Hallo Welt!</H1>
<p>Schon wieder ein kurzer Absatz mit ein wenig Text, der genauso nichtssagend ist wie der Absatz zuvor.</p>
</BODY>
</HTML>
我如何浏览BS4树并根据我有一个“H1”或“p”或其他类型的标记来进行某些修改?我想我需要一些switch语句来决定每个元素如何处理它。在
^{pr2}$
请尝试以下代码:
beautifulGroup标记对象有一个
name
属性,您可以检查它。例如,下面是一个函数,它通过向postwalk中的每个节点添加字符串“Done with this”+适当的标记名来转换树:注意。表示文本内容的}之类的属性,因此,如果您像上面一样遍历整个树,则需要检查是否确实手头有一个标记(我正在使用上面的
NavigableString
对象和表示注释的Comment
对象没有诸如name
或{hasattr
调用;我想您可以检查类型是bs4.element.Tag
)。在相关问题 更多 >
编程相关推荐