1

次のように、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タグのみを削除する方法はありますか?
どういうわけかこれらのタグを削除したいと思います:

<table style="width: 100%%" bgcolor="%s"><tr><td><font color="%s"><b>
and
</b></td></tr></table>

これを取得するには:

floatNumber

ここfloatNumberで、は浮動小数点数の文字列表現です。他のHTMLタグを変更したくありません。string.replaceまたはregexを使用することを考えていましたが、困惑しています。

4

2 に答える 2

2

str.replaceまたは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
于 2012-07-13T14:40:06.247 に答える
2

Beautiful Soupをインストールして使用できない場合(@ otto-allmendingerが提案したように、そうでない場合はBSが推奨されます):

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))
于 2012-07-13T14:43:20.117 に答える