使用BeautifulSoup获取SBA网站XLSX表格并合并数据时遇错误
爬取SBA灾难贷款XLSX数据并合并为带财年列的DataFrame
错误原因说明
你遇到的TypeError: 'NoneType' object is not iterable翻译为:类型错误:'NoneType'对象不可迭代,问题出在你用soup.find查找的jHSEzIJePQkATFwBbUD8j类div不存在,返回了None,导致后续遍历操作报错。
修正后的完整代码
import requests import pandas as pd from bs4 import BeautifulSoup # 目标网页地址 web_url = "https://www.sba.gov/document/report-sba-disaster-loan-data" html = requests.get(web_url).content soup = BeautifulSoup(html, 'html.parser') # 定位页面中所有表格行(适配页面实际结构) all_rows = soup.find_all('tr') # 存储各年份数据的列表 dfs = [] # 遍历行,筛选2010-2022年的XLSX链接 for row in all_rows: cells = row.find_all('td') # 确保行包含足够单元格,且存在年份和下载链接 if len(cells) >= 2: year_text = cells[0].get_text(strip=True) # 提取财年数字(如"FY 2022"中的2022) if year_text.startswith("FY "): year = int(year_text.split()[1]) if 2010 <= year <= 2022: link_tag = cells[1].find('a') # 确认是XLSX文件链接 if link_tag and link_tag.get('href').endswith('.xlsx'): xlsx_url = link_tag.get('href') # 补全相对链接的域名 if not xlsx_url.startswith('http'): xlsx_url = f"https://www.sba.gov{xlsx_url}" # 读取XLSX并添加财年列 print(f"处理{year}年数据中...") df = pd.read_excel(xlsx_url) df['year'] = year dfs.append(df) # 合并所有年份数据 merged_df = pd.concat(dfs, ignore_index=True) # 查看合并结果(可选) print(merged_df.head()) # 保存合并后的数据到本地(可选) merged_df.to_excel("sba_disaster_loans_2010-2022.xlsx", index=False)
代码要点
- 改用页面实际存在的
tr标签定位数据行,避免无效的class查找 - 精准筛选2010-2022财年的XLSX链接,自动补全相对链接
- 为每个年份的数据集添加
year标识列,最终合并为统一DataFrame
内容的提问来源于stack exchange,提问作者suedietrich
相关产品推荐
相关产品推荐

