You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium抓取数据到Pandas DataFrame时遇TimeoutException

问题原因与解决方案

核心问题:By.CLASS_NAME的使用错误

你的超时错误根源在于**By.CLASS_NAME不能接受多个空格分隔的类名**,Selenium会把整个字符串当作一个单一的类名去匹配,而网页中的表格是同时拥有多个类,所以永远找不到元素,触发超时。

修正步骤

1. 替换等待条件的定位方式

把By.CLASS_NAME换成By.CSS_SELECTOR,用点号连接多个类名:

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'table.table.table--inner-borders-all.table--left.table--striped.table--hover')))

或者更简洁的,用表格的一个唯一类来定位,减少冗余:

wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'table.table--striped')))

2. 修正BeautifulSoup的表格查找

同样,用CSS选择器查找表格更稳妥:

table = soup.select_one('table.table.table--inner-borders-all.table--left.table--striped.table--hover')

3. 可选优化:改用visibility_of_element_located

相比presence_of_element_located,visibility_of_element_located会等待元素可见,确保表格已经加载完成并渲染,避免获取到空的表格DOM:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'table.table--striped')))

完整修正后的代码

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd

def extract_data_from_table(table):
    countries = []
    regions_states = []
    start_dates = []
    end_dates = []

    if table is not None:
        for row in table.find_all('tr')[1:]:
            columns = row.find_all('td')

            if len(columns) >= 4:
                countries.append(columns[0].text.strip())
                regions_states.append(columns[1].text.strip())
                start_dates.append(columns[2].text.strip())
                end_dates.append(columns[3].text.strip())

        return pd.DataFrame({
            'Country': countries,
            'Regions/States': regions_states,
            'DST Start Date': start_dates,
            'DST End Date': end_dates
        }) 
    else:
        return None

url = "https://www.timeanddate.com/time/dst/2023.html"

options = Options()
options.add_argument("start-maximized")

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
wait = WebDriverWait(driver, 10)  # 无需1000秒,10秒足够覆盖正常加载

driver.get(url)

# 用CSS选择器等待表格可见
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'table.table--striped')))

soup = BeautifulSoup(driver.page_source, 'html.parser')
# 用CSS选择器查找目标表格
table = soup.select_one('table.table.table--inner-borders-all.table--left.table--striped.table--hover')

df = extract_data_from_table(table)

driver.quit()

if df is not None:
    print(df)

额外说明

  • 不要设置过长的超时时间,正常网页加载不会超过10秒,过长超时只会浪费时间。
  • 若不想依赖BeautifulSoup,也可以直接用Selenium遍历表格的行和列来提取数据,减少第三方库依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:52:53