从ASPX网站提取HTML表格返回None的问题求助
解决网页表格提取返回None的问题
问题描述
我尝试从以下网站提取表格:
https://serviciosede.mineco.gob.es/indeco/reports/verSerieGraf.aspx/?codigo=230400&frec=-1
该表格的列标题为“Fecha”和“Valor”。我通过以下HTML片段定位目标表格:
但运行以下代码后,
my_table返回None:import time import requests from bs4 import BeautifulSoup from selenium import webdriver driver4 = webdriver.Chrome() goe_url = "https://serviciosede.mineco.gob.es/indeco/reports/verSerieGraf.aspx/?codigo=230400&frec=-1" driver4.maximize_window() driver4.get(goe_url) time.sleep(5) content4 = driver4.page_source.encode('utf-8').strip() soup4 = BeautifulSoup(content4, "html.parser") my_table = soup4.find('table',{'class':'A6dc892817a884dcfbbecd587b047171f46'}) print(my_table)请问如何解决该问题?可能是我查询了错误的HTML元素,希望得到正确的代码以避免返回None。
问题原因及解决方案
核心问题
你代码中使用的表格class是
A6dc892817a884dcfbbecd587b047171f46,但实际目标表格的class是A43f22eb6dc4f401d849b49a4e6cd447e46,两者不匹配,这是返回None的直接原因。另外,这类动态渲染的网站还可能存在表格加载延迟、嵌套在iframe等情况,建议用更稳定的方式处理。
修正后的代码
from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver4 = webdriver.Chrome() goe_url = "https://serviciosede.mineco.gob.es/indeco/reports/verSerieGraf.aspx/?codigo=230400&frec=-1" driver4.maximize_window() driver4.get(goe_url) try: # 显式等待表格加载完成,替代固定sleep,更稳定 WebDriverWait(driver4, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "A43f22eb6dc4f401d849b49a4e6cd447e46")) ) content4 = driver4.page_source soup4 = BeautifulSoup(content4, "html.parser") my_table = soup4.find('table', {'class': 'A43f22eb6dc4f401d849b49a4e6cd447e46'}) # 提取并打印Fecha和Valor列数据 if my_table: rows = my_table.find_all('tr') for row in rows: cols = row.find_all('td') cols = [col.text.strip() for col in cols] if len(cols) >= 2: print(f"Fecha: {cols[0]}, Valor: {cols[1]}") else: print("未找到目标表格") finally: driver4.quit()额外说明
- Class匹配:动态生成的class可能会随网站更新变化,每次调试时建议重新查看页面源码确认目标元素的class。
- 显式等待:相比固定时长的
sleep,显式等待会在目标元素出现后立即执行,既高效又能避免因加载慢导致的元素未找到问题。- 数据过滤:目标表格有3列,我们只需要前两列(Fecha和Valor),提取时过滤掉多余列即可。
内容的提问来源于stack exchange,提问作者encore10
相关产品推荐
相关产品推荐

