使用python删除特定的html标记

2024-10-01 15:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我在HTML单元格中有一些HTML表格,如下所示:

miniTable='<table style="width: 100%%" bgcolor="%s">
               <tr><td><font color="%s"><b>%s</b></td></tr>
           </table>' % ( bgcolor, fontColor, floatNumber)

html += '<td>' + miniTable + '</td>'

有没有办法删除与这个迷你表相关的HTML标记,并且只删除这些HTML标记?
我想以某种方式删除这些标签:

^{pr2}$

要得到这个:

floatNumber

其中floatNumber是浮点数的字符串表示。我不想以任何方式修改其他HTML标记。我在想用字符串。替换或者正则表达式,但我被难住了。在


Tags: 字符串标记stylehtml方式tablewidthtr
2条回答

Do not use str.replace or regex.

使用像Beautiful Soup这样的html解析库,获取所需的元素和包含的文本。在

最后的代码应该是这样的

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc)

for t in soup.find_all("table"): # the actual selection depends on your specific code
    content = t.get_text()
    # content should be the float number

如果您无法安装和使用Beautiful Soup(否则首选BS,正如@otto allmendinger提议的那样):

import re
s = '<table style="width: 100%%" bgcolor="%s"><tr><td><font color="%s"><b>1.23</b></td></tr></table>'
result = float(re.sub(r"<.?table[^>]*>|<.?t[rd]>|<font[^>]+>|<.?b>", "", s))

相关问题 更多 >

    热门问题