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
相关产品推荐
相关产品推荐

