Beautifulsoup 网页表格的解析
生活随笔
收集整理的這篇文章主要介紹了
Beautifulsoup 网页表格的解析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Beautifulsoup 網頁表格的解析
眾所周知網頁的表格標簽里的文本需要按照表格的大小逐行逐列解析才能得到結構化的數據否則得到的內容則會錯位。
原始網頁:
代碼示例:
if len(potentialtable) > 0:##print(str(tableContent[1]).replace('\xa0',' '))for tab in potentialtable:x = (len(tab.findAll('tr')))startidx = tab.sourcelinestrtemp = ""relend = 0realtabsize = 0print(tab.name + "\t where is my way")if (tab.name == 'table'):realtabsize = realtabsize + 1for row in tab.findAll('tr')[0:x]:y = (len(row.findAll('td')))if y == 0 or y == 1:endidx = row.sourcelineelse:endidx = row.findAll('td')[-1].sourcelineprint('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'):continueelse:relend = i.sourcelineprint('relend\t'+str(relend))else:relend =0for 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 relendnewpd = 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日 質量要求: 工程質量符合達到國家現行有關施工質量驗收規范標準總結
以上是生活随笔為你收集整理的Beautifulsoup 网页表格的解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 江南银行一起富贷款申请条件
- 下一篇: 理财买基金风险大吗 不同类型基金有差别