如何不使用Pandas,用Beautiful Soup爬取维基表格生成CSV文件
修正方案
原有代码核心问题
- 缺少
csv库导入,调用csv.writer会直接报错 - 前3列的索引取值错误,第三列对应索引为
2而非3,误取了第四列数据 - 未处理表格中年份列的跨行(rowspan)属性,同一年份的多行数据只有第一行有年份单元格,后续行直接取
td[0]会出现列错位 - 表头硬编码不够灵活,可直接从表格的
<th>标签提取
可直接运行的修正代码
import requests import lxml import csv from bs4 import BeautifulSoup # 请求页面 url = 'https://en.wikipedia.org/wiki/List_of_winners_and_shortlisted_authors_of_the_Booker_Prize' page = requests.get(url).text # 解析页面 soup = BeautifulSoup(page, "lxml") # 定位目标表格 table = soup.find('table', class_="sortable wikitable") with open('output.csv', 'w', newline='', encoding='utf-8') as file: writer = csv.writer(file) # 提取表头前3列 headers = [th.get_text(strip=True) for th in table.find_all('th')[:3]] writer.writerow(headers) # 存储跨行的年份值,处理rowspan last_year = "" for tr in table.find_all('tr')[1:]: # 跳过表头行 tds = tr.find_all('td') if not tds: continue # 处理年份列跨行 if len(tds) == 4: # 有年份单元格的行 current_year = tds[0].get_text(strip=True) last_year = current_year author = tds[1].get_text(strip=True) title = tds[2].get_text(strip=True) else: # 无年份单元格的行,复用上次记录的年份 current_year = last_year author = tds[0].get_text(strip=True) title = tds[1].get_text(strip=True) writer.writerow([current_year, author, title])
关键逻辑说明
- 新增
encoding='utf-8'参数,避免特殊字符写入CSV时出现乱码 - 用
last_year变量存储上一个有效年份,解决年份列跨行导致的列数不一致问题 - 先判断每行的td数量,区分有年份和无年份的行,分别取值避免列错位
- 直接从表格的th标签提取表头,和原表格结构保持一致
内容的提问来源于stack exchange,提问作者Sackr1
相关产品推荐
相关产品推荐

