使用pyquery解析复杂网页表格的核心做法是结合css选择器定位表头与数据行,并通过索引映射将单元格内容重组为结构化字典。具体而言,先提取表头文本作为键,再遍历每一行数据,按列顺序填入值,最后过滤空值或无效行即可得到干净的列表。若遇到合并单元格(rowspan/colspan),需额外计算偏移量以对齐数据。

如何准确提取表头并建立列名映射
直接回答:通过选取第一行
下的| 或 |
元素获取表头文本,并将其存储为后续数据行的键列表。关键在于处理表头中的空白字符和特殊符号,确保键名唯一且可读。 
<!-- 假设HTML结构如下 -->
| Name |
Age |
City |
| Alice |
30 |
New York |
| Bob |
25 |
London |
# Python代码示例
from pyquery import PyQuery as pq
html = """
| Name |
Age |
City |
| Alice |
30 |
New York |
| Bob |
25 |
London |
"""
d = pq(html)
headers = [th.text() for th in d('#data-table thead tr th')]
rows = []
for tr in d('#data-table tbody tr').items():
cells = [td.text() for td in tr('td').items()]
if len(cells) == len(headers):
row_dict = dict(zip(headers, cells))
rows.append(row_dict)
print(rows)
# 输出: [{'Name': 'Alice', 'Age': '30', 'City': 'New York'}, {'Name': 'Bob', 'Age': '25', 'City': 'London'}]
如何处理包含合并单元格的复杂表格
直接回答:对于存在rowspan或colspan的表格,不能简单按行切片,而应维护一个当前行的“虚拟列”状态数组,根据合并属性动态跳过或填充已占用的单元格位置。这种方法能确保数据与表头正确对齐,避免错位。
Nodriver 异步无检测 Chrome 浏览器自动化 Python
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
下载

<!-- 复杂表格示例:包含合并单元格 -->
| Category |
Details |
| Sub1 |
Sub2 |
&thead>
| A |
Val1 |
Val2 |
# Python代码示例:处理合并单元格
from pyquery import PyQuery as pq
html_complex = """
| Category |
Details |
| Sub1 |
Sub2 |
&thead>
| A |
Val1 |
Val2 |
"""
def parse_complex_table(html_content):
d = pq(html_content)
# 获取所有表头行
thead_rows = d('#complex-table thead tr').items()
headers = []
col_index = 0
# 构建扁平化表头列表,处理rowspan和colspan
for tr in thead_rows:
ths = tr('th').items()
for th in ths:
rowspan = int(th.attr('rowspan') or 1)
colspan = int(th.attr('colspan') or 1)
text = th.text().strip()
for _ in range(colspan):
headers.append(text)
col_index += 1
# 注意:实际实现中可能需要更复杂的逻辑来追踪跨行
# 这里简化处理,仅展示基本思路
# 获取数据行
tbody_rows = d('#complex-table tbody tr').items()
result = []
for tr in tbody_rows:
tds = tr('td').items()
row_data = []
for td in tds:
rowspan = int(td.attr('rowspan') or 1)
colspan = int(td.attr('colspan') or 1)
text = td.text().strip()
# 如果单元格跨越多列,只取第一个值,其余视为重复或空
row_data.append(text)
# 在实际应用中,需要根据colspan调整后续列的处理
# 简化:假设每行数据长度与表头一致
if len(row_data) == len(headers):
result.append(dict(zip(headers, row_data)))
return result
print(parse_complex_table(html_complex))
# 输出可能因具体实现而异,此处仅为示意
当表格中存在缺失值或格式不一致时如何清洗数据
直接回答:在解析过程中,对每个单元格进行非空检查和类型转换,例如将数字字符串转为整数,去除前后空格,并将None或空字符串替换为默认值如NaN或空字符串。这样可以保证最终输出的数据结构一致,便于后续分析。
|
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!