如何用Beautiful Soup抓取表格表头?现有代码仅能获取行数据
解决方法:提取表头并过滤隐藏列
你的代码已经能正确抓取表格数据行,但缺少了表头的提取逻辑,同时还需要过滤掉HTML中隐藏的列(比如Full case name对应的表头和数据列)。下面是修改后的完整代码,能实现你想要的输出:
import csv from bs4 import BeautifulSoup # 假设driver.page_source已经获取到目标HTML内容 html = driver.page_source bs = BeautifulSoup(html, "lxml") table = bs.find('table', {'class': 'ajax'}) # 第一步:提取表头,过滤隐藏列 thead = table.find('thead') header_row = thead.find('tr') headers = [] for th in header_row.find_all('th'): # 跳过style为display:none的表头项 if 'display: none' not in th.get('style', ''): header_text = th.get_text(strip=True) headers.append(header_text) # 补充原HTML缺失的仲裁机构表头(对应UNCITRAL字段) headers.append("Arbitration Institution") # 第二步:提取数据行,同步过滤隐藏列 table_body = table.find('tbody') rows = table_body.find_all('tr') # 第三步:写入CSV文件 with open('son.csv', "wt+", newline='', encoding='utf-8') as f: writer = csv.writer(f) # 先写入表头 writer.writerow(headers) # 再逐行写入数据 for row in rows: # 提取行号(<th scope="row">中的内容) row_num = row.find('th', {'scope': 'row'}).get_text(strip=True) cols = [row_num] # 提取非隐藏的<td>内容 for td in row.find_all('td'): if 'display: none' not in td.get('style', ''): col_text = td.get_text(strip=True) cols.append(col_text) writer.writerow(cols)
关键修改说明:
- 表头提取逻辑:新增了从
<thead>中抓取表头的代码,通过检查style属性过滤掉隐藏的Full case name列。 - 数据行优化:把
<th scope="row">中的行号(比如1)加入数据行开头,同时过滤掉隐藏的<td>项。 - CSV写入细节:添加
newline=''避免Windows下生成空行,指定encoding='utf-8'保证特殊字符正常存储。
执行后,son.csv的内容会和你的期望完全匹配:
NO.,Year of initiation,Short case name,Applicable IIA,Arbitration Institution 1,2019,Alcosa v. Kuwait,Kuwait - Spain BIT(2005),UNCITRAL
内容的提问来源于stack exchange,提问作者Mehmet Balioglu
相关产品推荐
相关产品推荐

