1
<table class="table_grid">
<thead>
<tr>
<th>Name</th>
<th>User Name</th>
<th>Role</th>
<th>Branch</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name1</td>
<td>[email protected]</td>
<td>Processor</td>
<td></td>
<td><a href="/Account/EditUser?id=4c4e6455-7d27-4abf-93c9-5584f09674d5">Edit</a></td>
</tr>
<tr>
<td>First Name2</td>
<td>[email protected]</td>
<td>Officer</td>
<td></td>
<td><a href="/Account/EditUser?id=267e90eb-6fa4-4286-88d9-738913cdd7ea">Edit</a></td>
</tr>
</tbody>
</table>
このテーブルのテキストを解析してcsvファイルに書き込もうとしています。 csvに書き込むが、すべての文字は新しい列に終わる。 | F | i | r | s | t |私が探しているとき| First |。Beautifulsoupで解析した後にcsvに書き込むと、値が区切られたり、出力ファイルが空になります。
soup = BeautifulSoup(browser.page_source, 'html.parser')
table = soup.find('table', attrs={'class':'table_grid'})
with open('test1.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
for body in table.findAll('tr'):
rows = body.getText()
writer.writerow(rows)
これは私のコードです。私は次のようにこの問題を修正しようとした、ここで同様の問題を見て:
writer.writerow([rows])
しかし、これは空白のCSVファイルになりました。私がここで間違っていることは何ですか? - table('tr')
はtable.find_all('tr')
を行うための代替簡潔な方法である私はここにいくつかのショートカットを使用してい
with open('test1.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
for row in table('tr'):
writer.writerow([cell.get_text(strip=True) for cell in row(['td', 'th'])])
注:
これは間違いなくすべてのセルをその列に書き込んでいます。ありがとうございます。しかし、今では、それが前にそれらを引っ張っていたヘッダーが欠落しています。私は追加しますか:テーブルの行のために( 'th'):同様に? – nvachhan
@nvachhanよく、1つのアイデアは、すべての行に 'td'と' th'要素の両方を見つけることです - 更新された答えを見てください。 – alecxe
新しい回答があり、感謝しています。最後の質問、目的は何ですか:(ストリップ=真)?次回はパンダを試してみる。 – nvachhan