如何将html转换成csv,如何将HTML文本转换为CSV?

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

import csv

html = """

Basic EPS (Rs.)57.1848.84Diluted Eps (Rs.)56.4348.26"""

# Add the missing surrounding HTML

html = "

".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缺少封闭的

标记,因此为了能够正确地处理它,我在处理之前添加了这些标记。在

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

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

或者,但不建议:import re

html = """

Basic EPS (Rs.)57.1848.84!!Diluted Eps (Rs.)56.4348.26"""

with open('output.csv', 'wb') as f_output:

csv_output = csv.writer(f_output, delimiter='|')

tds = re.findall(r'\

(.*?)\', html)

for index in range(0, len(tds), 3):

csv_output.writerow(tds[index:index+3])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值