如何将HTML文本转换为CSV?

2024-04-25 08:48:20 发布

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

我在文本文件(.txt)中有以下HTML表:

<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr> 

CSV输出应如下所示:

^{pr2}$

Tags: righttxtbasichtmlepswidthtrclass
1条回答
网友
1楼 · 发布于 2024-04-25 08:48:20

尽管使用正则表达式可能很诱人,但我绝对建议您使用Python ^{}库来提供以下帮助:

from bs4 import BeautifulSoup
import csv

html = """<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr>"""

# Add the missing surrounding HTML
html = "<table><tr>{}</table>".format(html)
soup = BeautifulSoup(html, "html.parser")

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, delimiter='|')

    for tr in soup.find_all('tr'):
        csv_output.writerow([td.text for td in tr.find_all('td')])

给你:

^{pr2}$

您的HTML缺少封闭的<table><tr>和最后的</table>标记,因此为了能够正确地处理它,我在处理之前添加了这些标记。在

然后可以使用Python的^{}库将每一行单元格作为一个正确分隔的行写入输出CSV文件中。在

这是在python2.x上测试的,如果使用python3.x,则需要使用open('output.csv', 'w', newline='')。在


或者,但不建议:

import re

html = """<td class="det" colspan="1" width="40%">Basic EPS (Rs.)</td>
<td align="right" class="det">57.18</td>
<td align="right" class="det">48.84!!</td>
</tr>
<tr height="22px">
<td class="det" colspan="1" width="40%">Diluted Eps (Rs.)</td>
<td align="right" class="det">56.43</td>
<td align="right" class="det">48.26</td>
</tr>"""

with open('output.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output, delimiter='|')
    tds = re.findall(r'\<td.*?\>(.*?)\<\/td\>', html)

    for index in range(0, len(tds), 3):
        csv_output.writerow(tds[index:index+3])

相关问题 更多 >