解析 HTML 表格内容,提取表头和数据行。 参数 ---- html_content : str HTML 表格字符串,如 ... 返回 ---- tuple[List[str], List[List[str]]] (headers, rows) - 表头列名和数据行
(html_content: str)
| 1015 | |
| 1016 | |
| 1017 | def _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 | |
| 1074 | def _parse_html_table_simple(html_content: str) -> tuple[List[str], List[List[str]]]: |
no test coverage detected