これがhtmlです
<table>
<tr>
<td class="break">mono</td>
</tr>
<tr>
<td>c1</td>
<td>c2</td>
<td>c3</td>
</tr>
<tr>
<td>c11</td>
<td>c22</td>
<td>c33</td>
</tr>
<tr>
<td class="break">dono</td>
</tr>
<tr>
<td>d1</td>
<td>d2</td>
<td>d3</td>
</tr>
<tr>
<td>d11</td>
<td>d22</td>
<td>d33</td>
</tr>
</table>
今、私はcsvファイルでこのような出力が欲しいです:
mono c1 c2 c3
mono c11 c22 c33
dono d1 d2 d3
dono d11 d22 d33
しかし、私は次のような出力を取得しています:
mono
c1 c2 c3
c11 c22 c33
dono
d1 d2 d3
d11 d22 d33
これが私のコードです:
import codecs
from bs4 import BeautifulSoup
with codecs.open('dump.csv', "w", encoding="utf-8") as csvfile:
f = open("input.html","r")
soup = BeautifulSoup(f)
t = soup.findAll('table')
for table in t:
rows = table.findAll('tr')
for tr in rows:
cols = tr.findAll('td')
for td in cols:
csvfile.write(str(td.find(text=True)))
csvfile.write(",")
csvfile.write("\n")
この問題の解決にご協力ください。ありがとうございます。
編集:
詳細を説明します。ここで、追加する最初のセクション(mono、donoなど)を追加する必要があります。
ここでのルールは、新しい「ブレーク」クラスに遭遇しない限り、そのクラス内のテキストをその下のtrに追加する必要があるということです。