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日
质量要求: 工程质量符合达到国家现行有关施工质量验收规范标准