Selenium无法向搜索框输入内容,遇TimeoutException错误求助
问题解决:Selenium无法定位搜索输入框(TimeoutException)
核心原因
你使用的输入框ID typeahead-input-56352 是动态生成的,每次页面加载时ID的后缀数字都会变化,导致固定ID的定位方式失效,触发超时错误。
修复步骤
- 替换动态ID定位为稳定选择器:使用输入框的
name属性或placeholder等静态属性定位,这些属性不会随页面加载变化。 - 修正无头模式配置:代码中设置了
headless=True但未将配置传入ChromeDriver初始化,导致该配置未生效。 - 优化弹窗关闭的定位方式:使用更稳定的属性定位关闭按钮,避免依赖易变的class。
修正后的完整代码
# Import Dependencies from bs4 import BeautifulSoup as bs from selenium import webdriver from selenium.webdriver.support.ui import Select from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains import time options = webdriver.ChromeOptions() options.headless = True # 可选:添加无头模式下的必要参数,避免部分网站检测 options.add_argument("--window-size=1920,1080") options.add_argument("--disable-gpu") # 传入options初始化driver driver = webdriver.Chrome(options=options) driver.maximize_window() driver.get("https://broward.county-taxes.com/public/search/property_tax") # 用更稳定的方式关闭弹窗(根据aria-label定位关闭按钮) WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.XPATH, '//button[@aria-label="Close"]')) ).click() # 使用name属性定位搜索输入框(静态属性,不会变化) search_input = WebDriverWait(driver, 20).until( EC.visibility_of_element_located((By.NAME, "searchInput")) ) search_input.send_keys("2216 NW 6 PL FORT LAUDERDALE") # 点击搜索按钮 WebDriverWait(driver, 20).until( EC.element_to_be_clickable((By.ID, "search-icon")) ).click() # 后续操作... # driver.quit()
额外说明
- 优先使用
visibility_of_element_located而非element_to_be_clickable定位输入框,因为输入框只要可见就能输入,无需等待可点击状态,减少不必要的等待。 - 无头模式下建议添加
--window-size参数,确保页面元素布局正常加载,避免因窗口尺寸问题导致元素不可见。
内容的提问来源于stack exchange,提问作者Daremitsu
相关产品推荐
相关产品推荐

