Selenium+BeautifulSoup爬取代码if判断后print语句无输出问题排查
OpenTable爬取脚本中断问题排查与修复
核心根因
当前代码无任何异常捕获逻辑,触发未捕获的运行时错误时进程会直接终止,且Python输出缓冲区在进程被异常中断时不会自动刷新,就会表现为「if判断块执行后无后续打印输出」的现象,常见报错触发点:
booking节点为空:部分餐厅无div class="booking"子元素,restroom.find()返回None,调用booking.text直接抛出AttributeError- 分词结果不匹配预期:默认
word_tokenize结果索引1一定是可转成int的数字,但OpenTable的预订文案格式不统一,可能出现无数字的文案、数字位置偏移、分词后长度不足2的情况,会触发IndexError或ValueError
排查与修复步骤
1. 先捕获完整报错定位问题
在循环内添加异常捕获,同时强制刷新输出缓冲区,先跑一次拿到具体报错栈:
import traceback for i, restroom in enumerate(soup.find_all('div',class_='rest-row-info')): try: rest_name = restroom.find('span',class_='rest-row-name-text').text booking = restroom.find('div',class_='booking') # 先判断booking是否为空 if not booking: print(f"第{i}个餐厅无预订信息,跳过") continue words = list(word_tokenize(str(booking.text))) # 校验分词结果长度和目标位置是否为数字 if len(words) < 2 or not words[1].isdigit(): print(f"第{i}个餐厅预订文案格式异常:{words},跳过") continue if int(words[1]) > 100: print(booking.text) lists.extend([booking.text]) # 强制刷新输出缓冲区,避免异常中断时内容丢失 print('listers',len(lists), flush=True) print('this works fine', flush=True) print('this works fine', flush=True) except Exception as e: # 打印当前节点的完整报错,方便定位 print(f"第{i}个节点解析出错:") traceback.print_exc() continue
2. 预加载NLTK依赖
如果是首次调用word_tokenize,需要提前下载分词数据包,避免触发LookupError:
import nltk # 执行一次即可,下载完成后可注释掉 nltk.download('punkt_tab')
3. 补充空值判断
原有代码中rest_name = restroom.find('span',class_='rest-row-name-text').text同样存在空值风险,建议提前判断该元素是否存在,避免触发同类报错。
内容的提问来源于stack exchange,提问作者hft654
相关产品推荐
相关产品推荐

