MCPcopy Create free account
hub / github.com/OpenDCAI/Paper2Any / _parse_html_table

Function _parse_html_table

dataflow_agent/utils_common.py:1017–1071  ·  view source on GitHub ↗

解析 HTML 表格内容,提取表头和数据行。 参数 ---- html_content : str HTML 表格字符串,如 ... 返回 ---- tuple[List[str], List[List[str]]] (headers, rows) - 表头列名和数据行

(html_content: str)

Source from the content-addressed store, hash-verified

1015
1016
1017def _parse_html_table(html_content: str) -> tuple[List[str], List[List[str]]]:
1018 """
1019 解析 HTML 表格内容,提取表头和数据行。
1020
1021 参数
1022 ----
1023 html_content : str
1024 HTML 表格字符串,如 <table>...</table>
1025
1026 返回
1027 ----
1028 tuple[List[str], List[List[str]]]
1029 (headers, rows) - 表头列名和数据行
1030 """
1031 try:
1032 from bs4 import BeautifulSoup
1033 except ImportError:
1034 log.warning("[_parse_html_table] BeautifulSoup 未安装,使用简单解析")
1035 return _parse_html_table_simple(html_content)
1036
1037 try:
1038 soup = BeautifulSoup(html_content, 'html.parser')
1039 table = soup.find('table')
1040
1041 if not table:
1042 log.warning("[_parse_html_table] 未找到 table 标签")
1043 return [], []
1044
1045 # 提取所有行
1046 rows_data = []
1047 for tr in table.find_all('tr'):
1048 row = []
1049 for cell in tr.find_all(['td', 'th']):
1050 # 处理 colspan
1051 colspan = int(cell.get('colspan', 1))
1052 cell_text = cell.get_text(strip=True)
1053 row.append(cell_text)
1054 # 如果有 colspan,添加空单元格
1055 for _ in range(colspan - 1):
1056 row.append('')
1057 if row: # 只添加非空行
1058 rows_data.append(row)
1059
1060 if not rows_data:
1061 return [], []
1062
1063 # 第一行作为表头
1064 headers = rows_data[0]
1065 data_rows = rows_data[1:] if len(rows_data) > 1 else []
1066
1067 return headers, data_rows
1068
1069 except Exception as e:
1070 log.error(f"[_parse_html_table] 解析失败: {e}")
1071 return _parse_html_table_simple(html_content)
1072
1073
1074def _parse_html_table_simple(html_content: str) -> tuple[List[str], List[List[str]]]:

Callers 1

Calls 4

_parse_html_table_simpleFunction · 0.85
get_textMethod · 0.80
findMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected