使用美丽汤提取标签之间的<br/>文本以分隔熊猫列



我有一个HTML数据表抓取(见下面的示例(,我正在尝试将其保存到熊猫df中。我可以成功提取每一行并将每个 HTML<td>列解析为 df 中的单独列(请参阅下面的代码(。我遇到的问题是,在某些列中,有多个数据项由<br><nobr>分隔。由<br><nobr>分隔的每个元素都应放入其自己的单独 df 列中(请参阅下面的当前和所需的 df 列(。例如,当前代码将日期和时间数据输出为09.10.201918:5020:25,而不是将日期09.10.2019、出发时间18:50和到达时间20:25分隔到df中自己的列中。

示例 HTML 行

<tr valign="top"><td align="right" class="liste_gross">548<br/></td><td class="liste"><nobr>02.01.2018</nobr>
<br/>08:45<br/>14:55 </td><td class="liste_gross"><b>MEL</b><br/></td><td class="liste"><b>Melbourne</b><br/>
Australia<br/>Tullamarine</td><td class="liste_gross"><b>HKG</b><br/></td><td class="liste"><b>Hong Kong</b><br/>
China<br/>International</td><th align="right" class="liste_gross"><table border="0" cellpadding="0" cellspacing="0">
<tr><td align="right">7,420 </td><td>km</td></tr><tr><td align="right">9:25 </td><td>h</td></tr></table>
</th><td class="liste">Cathay Pacific<br/>CX34</td><td class="liste">A350-900<br/>B-LRR</td>
<td class="liste">32A/Window<br/><small>EconomyPlus<br/>Passenger<br/>Personal</small></td><td class="liste">
<br/><select onchange="if (this.value != 'NIL') location.href=this.value;" style="width:60px;">
<option value="NIL">Flight</option><option value="?go=flugdaten_edit&amp;id=14619399&amp;dbpos=0">edit</option>
<option value="NIL">----------</option><option value="?go=flugdaten_loeschen&amp;id=14619399&amp;dbpos=0">delete
</option></select></td></tr>

具有当前列名的 Python 代码

soup = BeautifulSoup(response, 'html.parser') # Parse the response using BeautifulSoup
table = soup.find('table', attrs={'cellspacing' : 2}) # Select the only table with this attribute
rows = table.find_all('tr')
for row in rows:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) # Get rid of empty values
dftable = pd.DataFrame(data, columns = ['flightno', 'date.timedept.timearr', 'codedept',
'citydept.countrydept.namedept', 'codearr', 'cityarr.countryarr.namearr',
'dist', 'distunits', 'time', 'timeunits', 'airline.flightno',
'manuf.type.rego', 'seat.loc.class.pass.reason', 'inputcol'])
dftable = dftable.dropna()  # Drop incomplete rows

所需的列名称列表

dftable = pd.DataFrame(data, columns = ['flightno', 'date', 'timedept', 'timearr', 'codedept',
'citydept', 'countrydept', 'namedept', 'codearr', 'cityarr', 'countryarr',
'namearr', 'dist', 'distunits', 'time', 'timeunits', 'airline', 'flightno',
'manuf', 'type', 'rego', 'seat', 'loc', 'class', 'pass', 'reason', 'inputcol'])

也许这可以帮助你...你可以像这样使用 pd.read_html for parse html 表:

from bs4 import BeautifulSoup
import pandas as pd
import re
soup = BeautifulSoup(open("table.html"), "lxml")
# Replace <br> by | ...
s = re.sub('<brs*/>','|', str(soup))
df_table = pd.read_html(s)
# To dataframe
df_table=df_table[0]
df_table.columns = ['flightno', 'fulldate','codedept','full_dept', 'countrydept', 'full_arr', 'KM', 'date_plane', 'date_plane_2','date_pass', 'inputcol']
#Split columns using value |
df_table[['date','timedept','timearr']] = df_table['fulldate'].str.split('|', expand=True)
df_table[['citydept','countrydept','namedept']] = df_table['full_dept'].str.split('|', expand=True)
df_table[['cityarr','countryarr','namearr']] = df_table['full_arr'].str.split('|', expand=True)
df_table[['airline','flightno']] = df_table['date_plane'].str.split('|', expand=True)
df_table[['manuf','type']] = df_table['date_plane_2'].str.split('|', expand=True)
df_table[['full_seat','class','pass','reason']] = df_table['date_pass'].str.split('|', expand=True)
df_table[['seat', 'loc']] = df_table['full_seat'].str.split('/', expand=True)
#Drop columns not necessary
df_table.drop(['fulldate','full_dept','full_arr','date_plane','date_plane_2','date_pass','full_seat'], axis=1, inplace=True)
#print(df_table)
df_table.to_csv('table_to_csv.csv')

表.html包含:

<!DOCTYPE html>
<html>
<body>
<table  border='1'>
<tr valign="top"><td align="right" class="liste_gross">548<br/></td><td class="liste"><nobr>02.01.2018</nobr>
<br/>08:45<br/>14:55 </td><td class="liste_gross"><b>MEL</b><br/></td><td class="liste"><b>Melbourne</b><br/>
Australia<br/>Tullamarine</td><td class="liste_gross"><b>HKG</b><br/></td><td class="liste"><b>Hong Kong</b><br/>
China<br/>International</td><th align="right" class="liste_gross"><table border="0" cellpadding="0" cellspacing="0">
<tr><td align="right">7,420 </td><td>km</td></tr><tr><td align="right">9:25 </td><td>h</td></tr></table>
</th><td class="liste">Cathay Pacific<br/>CX34</td><td class="liste">A350-900<br/>B-LRR</td>
<td class="liste">32A/Window<br/><small>EconomyPlus<br/>Passenger<br/>Personal</small></td><td class="liste">
<br/><select onchange="if (this.value != 'NIL') location.href=this.value;" style="width:60px;">
<option value="NIL">Flight</option><option value="?go=flugdaten_edit&amp;id=14619399&amp;dbpos=0">edit</option>
<option value="NIL">----------</option><option value="?go=flugdaten_loeschen&amp;id=14619399&amp;dbpos=0">delete
</option></select></td></tr></table>
</body>
</html>

这是一个正则表达式 + SimplifiedDoc 解决方案

import re
from simplified_scrapy.simplified_doc import SimplifiedDoc 
html='''<table cellspacing="2"><tr valign="top"><td align="right" class="liste_gross">548<br/></td><td class="liste"><nobr>02.01.2018</nobr>
<br/>08:45<br/>14:55 </td><td class="liste_gross"><b>MEL</b><br/></td><td class="liste"><b>Melbourne</b><br/>
Australia<br/>Tullamarine</td><td class="liste_gross"><b>HKG</b><br/></td><td class="liste"><b>Hong Kong</b><br/>
China<br/>International</td><th align="right" class="liste_gross"><table border="0" cellpadding="0" cellspacing="0">
<tr><td align="right">7,420 </td><td>km</td></tr><tr><td align="right">9:25 </td><td>h</td></tr></table>
</th><td class="liste">Cathay Pacific<br/>CX34</td><td class="liste">A350-900<br/>B-LRR</td>
<td class="liste">32A/Window<br/><small>EconomyPlus<br/>Passenger<br/>Personal</small></td><td class="liste">
<br/><select onchange="if (this.value != 'NIL') location.href=this.value;" style="width:60px;">
<option value="NIL">Flight</option><option value="?go=flugdaten_edit&amp;id=14619399&amp;dbpos=0">edit</option>
<option value="NIL">----------</option><option value="?go=flugdaten_loeschen&amp;id=14619399&amp;dbpos=0">delete
</option></select></td></tr></table>
'''
doc = SimplifiedDoc(html)
table = doc.getElement('table',attr="cellspacing",value="2")
rows = table.trs # get all rows
data = []
for row in rows:
arr = []
# cols = row.tds # get all tds
cols = row.children # td and th
i = 0
while i<len(cols):
if i==1: # for example
items = re.split('<brs*/>',cols[i].html)
for item in items:
arr.append(doc.removeHtml(item))
elif cols[i].tag=='th': # deal it by yourself
tds = cols[i].tds
print (tds)
else:
arr.append(cols[i].text)
i+=1
data.append(arr)
print (data) # [['548', '02.01.2018', '08:45', '14:55', 'MEL', 'MelbourneAustraliaTullamarine', 'HKG', 'Hong KongChinaInternational', 'Cathay PacificCX34', 'A350-900B-LRR', '32A/WindowEconomyPlusPassengerPersonal', 'Flightedit----------delete']]

相关内容

最新更新