代码长时间运行后出现AttributeError: 'NoneType'无text属性错误求解决
问题原因与解决方案
错误根源
报错是因为soup.find('p', attrs={'style':..."})返回了None(找不到匹配的p标签),直接链式调用.text触发了AttributeError。长时间运行后出现这个问题,大概率是两种情况:
- 网站反爬机制触发,返回的页面内容和预期不符(比如验证码页、空白页)
- 页面结构更新,目标p标签的style属性发生了变化(比如空格、顺序调整)
修复步骤与代码优化
1. 先校验请求有效性
先确认请求是否成功拿到正常页面,避免无效页面解析;
2. 避免链式调用,先判断元素是否存在
不要直接在find后加.text,先把结果存到变量里,判断存在后再操作;
3. 优化选择器(可选但推荐)
用style属性定位太脆弱,建议换更稳定的方式,比如结合父元素、类名或文本内容定位。
修改后的完整代码:
import time from bs4 import BeautifulSoup def check_seatNumber(seatNumber): response = requestSeatNumber(seatNumber) # 检查请求是否成功 if response.status_code != 200: print(f"座位号 {seatNumber} 请求失败,状态码:{response.status_code}") return seatNumber soup = BeautifulSoup(response.content, 'html.parser') # 显式指定解析器更稳妥 # 用部分样式匹配替代完全匹配,提升兼容性 target_p = soup.find('p', style=lambda value: value and 'color: red' in value and 'font-size: 14px' in value) if not target_p: print(f"座位号 {seatNumber} 未找到目标标签,可能页面结构变化或被反爬") return seatNumber # 用strip()去除首尾空白,避免空格干扰空文本判断 is_empty = target_p.text.strip() == '' print(f"座位号 {seatNumber} 文本为空:{is_empty}") if is_empty: student_inform(soup) return None # 返回None表示有效,对应调用处的`if not num_status` else: return seatNumber # 调用处添加延时,降低反爬风险 start = 1000 finish = 2000 for num in range(start, finish): print(f"Checking {num}...") num_status = check_seatNumber(num) if not num_status: print(f'{num} is valid') else: print(f'{num} is invalid') time.sleep(1) # 每次请求后延时1秒,可根据情况调整
额外注意事项
- 反爬应对:在
requestSeatNumber函数里添加合理的请求头(比如User-Agent模拟浏览器),必要时使用代理IP; - 选择器优化:如果能找到目标p标签的父元素class/id,比如
soup.select_one('.warning-box p'),比style定位可靠得多; - 异常捕获:可以在关键代码块外加
try-except,避免单个请求失败导致整个程序终止。
内容的提问来源于stack exchange,提问作者aya abdalsalam
相关产品推荐
相关产品推荐

