Python AttributeError报错求助:网页表格爬取失败
问题排查与解决方案
错误核心原因
你碰到的AttributeError: 'NoneType' object has no attribute 'find_all',本质是代码里的table变量为None——也就是BeautifulSoup没找到你指定的class="table-stats"表格。常见触发场景有两个:
- 网站反爬机制拦截了你的请求,返回的不是正常页面内容(比如验证码页、空白页)
- 网页结构已更新,目标表格的class不再是
table-stats
具体修复步骤
1. 先验证请求是否正常
在请求后添加状态码检查,确认网站是否正常响应:
page = requests.get(url) print(page.status_code) # 正常响应应该返回200
如果返回403/404等非200状态码,说明请求被拦截,需要添加请求头模拟浏览器。
2. 添加请求头绕过基础反爬
多数网站会校验User-Agent字段,默认requests的请求头会被识别为机器人。修改请求部分:
headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } page = requests.get(url, headers=headers)
3. 确认表格的正确选择器
手动打开目标网页,按F12调出开发者工具,定位主表格后查看它的实际class或属性。比如当前该页面主表格的class可能是table table--stats table--overflow(以实际网页结构为准),调整find参数:
# 替换原有的表格查找代码,使用当前网页的正确选择器 table = soup.find("table", class_="table--stats")
4. 添加容错判断避免崩溃
在处理表格前先判断是否找到,防止直接调用find_all报错:
if not table: print("未找到目标表格,请检查选择器或请求是否正常") exit()
修改后的完整代码
import requests from bs4 import BeautifulSoup import pandas as pd # 带请求头发起请求 url = "https://www.rotowire.com/daily/nba/optimizer.php?site=FanDuel" headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36" } page = requests.get(url, headers=headers) # 检查请求状态 if page.status_code != 200: print(f"请求失败,状态码:{page.status_code}") exit() # 解析页面 soup = BeautifulSoup(page.content, "html.parser") # 查找目标表格(注意:需根据当前网页结构确认class) table = soup.find("table", class_="table--stats") # 容错判断 if not table: print("未找到目标表格,请检查选择器是否正确") exit() # 提取表格数据 data = [] rows = table.find_all("tr") for row in rows: cols = row.find_all("td") cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # 转换为DataFrame(容错空数据) if len(data) < 2: print("表格数据为空") exit() df = pd.DataFrame(data[1:], columns=data[0]) # 合并现有数据并去重 existing_df = None try: existing_df = pd.read_csv("nba_optimizer.csv") df = pd.concat([existing_df, df]).drop_duplicates() except FileNotFoundError: pass # 写入CSV df.to_csv("nba_optimizer.csv", index=False, mode="a", header=not bool(existing_df))
内容的提问来源于stack exchange,提问作者fouraces
相关产品推荐
相关产品推荐

