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

Python Selenium点击单选按钮后搜索输入报错求助

问题:Selenium操作合租网站时出现StaleElementReferenceException错误

程序目标

向合租网站输入一组邮政编码,返回每个邮编对应的求租房源和可租房源数量。

遇到的问题

切换单选按钮(从求租房源到可租房源)后,复用之前获取的search_box元素调用send_keys()时失效,抛出StaleElementReferenceException错误,错误栈如下:

Traceback (most recent call last):
  File "c:\Users\SS\Dropbox\PC\Programming\Python Programming\Web Automation\WebScraper.py", line 34, in <module>
    search_box.send_keys(postcode, Keys.ENTER)
  File "C:\Users\SS\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 303, in send_keys
    self._execute(
  File "C:\Users\SS\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webelement.py", line 572, in _execute
    return self._parent.execute(command, params)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SS\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\webdriver.py", line 448, in execute
    self.error_handler.check_response(response)
  File "C:\Users\SS\AppData\Local\Programs\Python\Python312\Lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 232, in check_response    
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: stale element not found

相关代码片段

wanted_button = driver.find_element(By.ID, "flatshare_type-wanted")
driver.execute_script("arguments[0].checked = true;", wanted_button)
search_box = driver.find_element(By.ID, "search_by_location_field")
print(wanted_button)
search_box.send_keys(postcode, Keys.ENTER)
time.sleep(5) 

rent_button = driver.find_element(By.ID, "flatshare_type-offered")
driver.execute_script("arguments[0].checked = true;", rent_button)
search_box.send_keys(postcode, Keys.ENTER)
print(rent_button)
time.sleep(5)

背景信息

  • 单选按钮使用click()方法无效,改用execute_script()设置选中状态;
  • 程序偶尔会莫名关闭,重启后恢复正常;
  • 运行前出现USB相关错误,不确定是否影响当前问题:
[34088:37684:0512/205949.001:ERROR:services\device\usb\usb_descriptors.cc:146] Failed to read length for configuration 1.
[34088:37684:0512/205949.037:ERROR:services\device\usb\usb_descriptors.cc:146] Failed to read length for configuration 2.
[34088:37684:0512/205949.037:ERROR:services\device\usb\usb_descriptors.cc:105] Failed to read all configuration descriptors. Expected 3, got 1.
[34088:37684:0512/205949.037:ERROR:components\device_event_log\device_event_log_impl.cc:202] [20:59:49.038] USB: usb_device_win.cc:95 Failed to read descriptors from \\?\usb#vid_0b95&pid_1790#00a226a5#{a5dcbf10-6530-11d2-901f-00c04fb951ed}

解决方案

1. 修复StaleElementReferenceException错误

这个错误的核心原因是:切换单选按钮后,页面可能重新渲染了搜索框元素,之前获取的search_box对象已经和当前页面的元素失去绑定(变成"过时"元素)。

修改方法:每次操作单选按钮后,重新查找搜索框元素,不要复用之前的对象:

# 处理求租房源
wanted_button = driver.find_element(By.ID, "flatshare_type-wanted")
driver.execute_script("arguments[0].checked = true;", wanted_button)
# 重新获取搜索框
search_box = driver.find_element(By.ID, "search_by_location_field")
search_box.send_keys(postcode, Keys.ENTER)
time.sleep(5) 

# 处理可租房源
rent_button = driver.find_element(By.ID, "flatshare_type-offered")
driver.execute_script("arguments[0].checked = true;", rent_button)
# 重新获取搜索框
search_box = driver.find_element(By.ID, "search_by_location_field")
search_box.send_keys(postcode, Keys.ENTER)
time.sleep(5)

2. 优化等待逻辑(替代time.sleep)

time.sleep()是固定时长等待,容易因页面加载慢导致问题,建议改用Selenium的显式等待,等待元素可交互后再操作,提升稳定性:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 处理求租房源
wanted_button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "flatshare_type-wanted"))
)
driver.execute_script("arguments[0].checked = true;", wanted_button)
# 等待搜索框可交互
search_box = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "search_by_location_field"))
)
search_box.clear()  # 清空之前的输入内容
search_box.send_keys(postcode, Keys.ENTER)
# 等待结果页面加载完成(示例:等待结果列表元素出现)
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".listing-results"))
)

# 处理可租房源
rent_button = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, "flatshare_type-offered"))
)
driver.execute_script("arguments[0].checked = true;", rent_button)
# 重新等待搜索框可交互
search_box = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.ID, "search_by_location_field"))
)
search_box.clear()
search_box.send_keys(postcode, Keys.ENTER)
WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".listing-results"))
)

3. USB错误说明

这些USB错误是Chrome浏览器驱动的日志,和你的业务操作无关,不会影响程序功能,可以直接忽略。

4. 解决程序莫名关闭问题

  • 检查代码中是否有未捕获的异常导致程序崩溃;
  • 确保Chrome浏览器和ChromeDriver版本完全匹配;
  • 启动driver时添加参数,保持浏览器不会自动关闭:
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("detach", True)  # 保持浏览器窗口打开
driver = webdriver.Chrome(options=options)

内容的提问来源于stack exchange,提问作者Human2.0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 03:05:19