Beautifulsoup 网页表格的解析

                               Beautifulsoup 网页表格的解析

众所周知网页的表格标签里的文本需要按照表格的大小逐行逐列解析才能得到结构化的数据否则得到的内容则会错位。

原始网页:

代码示例:

    if len(potentialtable) > 0:
        ##print(str(tableContent[1]).replace('\xa0',' '))
        for tab in potentialtable:
            x = (len(tab.findAll('tr')))
            startidx = tab.sourceline
            strtemp = ""
            relend = 0
            realtabsize = 0
            print(tab.name + "\t where is my way")
            if (tab.name == 'table'):
                realtabsize = realtabsize + 1
            for row in tab.findAll('tr')[0:x]:
                y = (len(row.findAll('td')))
                if y == 0 or y == 1:
                    endidx = row.sourceline
                else:
                    endidx = row.findAll('td')[-1].sourceline
                    print('endidx\t'+str(endidx))
                    lastrow = row.findAll('td')[-1]
                    lenchild=len(lastrow.find_all(lambda x: x.name != '', recursive=False))
                    if lenchild >0:
                        for i in lastrow.descendants:
                            typename = str(type(i)).replace("<class 'bs4.element.", '').replace("'>", '')
                            if (typename == 'NavigableString'):
                                continue
                            else:
                                
                                relend = i.sourceline
                                print('relend\t'+str(relend))
                    else:
                        relend =0

                for td in row.findAll('td')[0:y]:
                    strtemp = strtemp + td.get_text().replace('\n', '') + "\t"
                strtemp = strtemp.rstrip('\t') + "\01"  # + "^"
                        relend = endidx if (relend == 0) else relend
            newpd = pd.DataFrame({"bindid": bidid + '_' + str(catalog)[::-1][0], "start": startidx, "end": relend,
                                  "cont": strtemp.replace('\xa0', ' '), 'catalog': 4, 'realbindid': bidid,
                                  'bindkind': str(catalog)[::-1][0]}, index=["0"])
            df_htmlreplace = df_htmlreplace.append(newpd, ignore_index=True, sort=True)

执行结果(\t分割):

 合同编号: 	 BZGC2019042-01 
 合同名称: 	 消防改造工程第1标段 
 标段(包)名称: 	 消防改造工程第1标段 
 标段(包)编号: 	 BZGC2019042-01 
 合同甲方名称: 	 人民医院 
 合同乙方名称: 	 金沙滩科技有限公司 
 合同金额: 	 852633.7 
 金额单位: 	 元 
 合同期限(天): 	 100 
 合同签署日期: 	 2019年08月19日 
 合同完成日期: 	 2020年04月30日 
 质量要求: 	 工程质量符合达到国家现行有关施工质量验收规范标准

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShenLiang2025

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值