html = """ <table class=""> <tr> <th>名前</th> <th>年齢</th> </tr> <tr> <td>John</td> <td>33</td> </tr> </table> <table class=""> <tr> <th>名前</th> <th>年齢</th> </tr> <tr> <td>masaki</td> <td>31</td> </tr> </table> <table class=""> <tr> <th>名前</th> <th>年齢</th> </tr> <tr> <td>Ohn</td> <td>22</td> </tr> </table> """
と3つのテーブルが1つのhtml内にあります。
import csv from bs4 import BeautifulSoup #上のテーブルが来る soup = BeautifulSoup(html, "html.parser") content = [tag.string for tag in soup.find_all("td")] items = [content[i:i+2] for i in range(0, len(content), 2)] with open("tmp.csv", "w", encoding="utf-8") as f: writer = csv.writer(f) writer.writerows(items)
とコードを書いて実行すると、
名前,年齢 John,33 名前,年齢 masaki,31 名前,年齢 Ohni,22
のように名前,年齢は3回も記入されてしまいます。
tmp.csv内に1回だけ名前,年齢を記入して、
名前,年齢 John,33 masaki,31 Ohni,22
のような書き込みにしたいのですが、どのように書いたら1回だけ書き込まれますか?
質問文のソースコードを実行しましたが、ヘッダー行が複数件書き込まれる問題を再現できませんでした。
回答2件
あなたの回答
tips
プレビュー