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

Selenium Python中TimeoutException问题:无法点击Siswa元素

解决Selenium点击“Siswa”元素时的TimeoutException问题

针对你遇到的TimeoutException,以下是关键修复点和修改后的代码:

问题核心原因

  1. 点击学校名称后页面会跳转,但原代码未等待页面跳转完成就立即查找元素,导致目标元素还未加载
  2. “Siswa”元素位于页面下方,未滚动到可视区域时,Selenium无法检测到元素的可点击状态
  3. 原定位器依赖href属性,不如直接用元素文本定位精准

修复方案

  • 等待页面跳转完成:通过EC.url_changes确认页面URL更新,确保学校详情页加载完成
  • 滚动到目标元素:使用JS脚本将元素滚动到可视区域,避免因元素不可见导致的交互失败
  • 更换精准定位器:用文本定位//a[text()='Siswa']替代href属性定位,提升定位准确性
  • 适当延长等待时长:根据页面实际加载速度调整等待时间

修改后的代码

import openpyxl
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import pyautogui as py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = 'https://sekolah.data.kemdikbud.go.id/'
chrome_options = Options()
chrome_options.add_experimental_option("detach",True)
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                          options=chrome_options)
driver.get(url)

# 选择地区
x_element = driver.find_element(By.ID, 'kode_kabupaten')
x = Select(x_element)
x.select_by_visible_text("Prov. Jawa Timur - Kota Surabaya")

# 选择学校类型
y_element = driver.find_element(By.ID, 'bentuk_pendidikan')
y = Select(y_element)
y.select_by_visible_text("SMA")

# 提交查询
submit = driver.find_element(By.XPATH, '//button[text()="Cari Sekolah"]')
submit.click()

# 点击学校名称,记录当前URL用于判断跳转
current_url = driver.current_url
sch_name = driver.find_element(By.XPATH, '//*[@class="text-info"]/b')
sch_name.click()

# 等待页面跳转完成,确保详情页加载完毕
WebDriverWait(driver, 15).until(EC.url_changes(current_url))

# 定位Siswa元素,等待元素存在
siswa_locator = (By.XPATH, '//a[text()="Siswa"]')
siswa_link = WebDriverWait(driver, 15).until(EC.presence_of_element_located(siswa_locator))

# 滚动到元素可视区域
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", siswa_link)

# 等待元素可点击后执行点击操作
WebDriverWait(driver, 15).until(EC.element_to_be_clickable(siswa_locator)).click()

额外提示

  • 如果仍出现超时,可尝试添加隐式等待(注意不要与显式等待混用):driver.implicitly_wait(10)
  • 爬取表格数据时,可通过EC.presence_of_all_elements_located等待表格内容完全加载后再提取数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:47:05