You need to enable JavaScript to run this app. Beautiful Soup代码中for循环内打印语句不执行问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Beautiful Soup代码中for循环内打印语句不执行问题排查

问题原因

  • 核心原因是选择器配置错误:目标页面中view-content是表格外层div的类名,不是表格行<tr>的类名,soup.find_all('tr',class_='view-content')会返回空列表,自然不会进入第一个for循环,所以naseef3没有输出。
  • 就算调整了外层选择器,内层循环的写法也存在逻辑问题:遍历行的时候直接从整个soup对象查找td,而非从当前遍历的行对象中查找,会导致重复获取到第一个匹配的td元素,不符合遍历每行数据的需求。
  • 额外注意:原代码没有加页面加载等待逻辑,可能存在页面还未渲染完成就开始解析HTML的情况,也会导致元素匹配失败。

修正后的代码示例

from bs4 import BeautifulSoup
import numpy as np
import requests 
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from nltk.tokenize import sent_tokenize,word_tokenize

driver = webdriver.Firefox(executable_path=r'D:\geckodriver.exe')
driver.get("https://www.tsa.gov/coronavirus/passenger-throughput")
# 等待表格加载完成,最多等待10秒
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'table')))

def TSA_travel_numbers(html):
    print('NASEEF')
    soup = BeautifulSoup(html,'lxml')
    print('naseef2')
    # 先定位到外层的view-content容器,再查找内部的tr元素
    content_div = soup.find('div', class_='view-content')
    for i,rows in enumerate(content_div.find_all('tr')):
        print('naseef3')
        # 从当前行对象中查找对应td,避免全文档重复查找
        td = rows.find('td', header = 'view-field-2021-throughput-table-column')
        if not td:
            continue
        print('naseef4')
        number = td.text.strip()
        if not number:
            continue
        print(number)

TSA_travel_numbers(driver.page_source)
driver.quit()

内容的提问来源于stack exchange,提问作者hft654

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 10:36:04