如何将html转换成csv,如何将HTML表格转换为CSV?

这是一个简单的Python程序,用于从HTML中解析表格数据。该程序通过定义一个继承自HTMLParser的类实现,可以处理基本的表格结构并将数据输出为纯文本格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Yuval..

9

这是我编写的一个简短的Python程序来完成这项任务.它是在几分钟内编写的,所以它可能会变得更好.不确定它将如何处理嵌套表(可能它会做坏事)或多个表(可能它们只是一个接一个地出现).它没有处理colspan或rowspan.请享用.

from HTMLParser import HTMLParser

import sys

import re

class HTMLTableParser(HTMLParser):

def __init__(self, row_delim="\n", cell_delim="\t"):

HTMLParser.__init__(self)

self.despace_re = re.compile(r'\s+')

self.data_interrupt = False

self.first_row = True

self.first_cell = True

self.in_cell = False

self.row_delim = row_delim

self.cell_delim = cell_delim

def handle_starttag(self, tag, attrs):

self.data_interrupt = True

if tag == "table":

self.first_row = True

self.first_cell = True

elif tag == "tr":

if not self.first_row:

sys.stdout.write(self.row_delim)

self.first_row = False

self.first_cell = True

self.data_interrupt = False

elif tag == "td" or tag == "th":

if not self.first_cell:

sys.stdout.write(self.cell_delim)

self.first_cell = False

self.data_interrupt = False

self.in_cell = True

def handle_endtag(self, tag):

self.data_interrupt = True

if tag == "td" or tag == "th":

self.in_cell = False

def handle_data(self, data):

if self.in_cell:

#if self.data_interrupt:

# sys.stdout.write(" ")

sys.stdout.write(self.despace_re.sub(' ', data).strip())

self.data_interrupt = False

parser = HTMLTableParser()

parser.feed(sys.stdin.read())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值