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

Selenium点击编辑按钮触发500错误及TimeoutException问题求助

问题描述

我编写的复制粘贴机器人其余功能正常,但点击编辑按钮时出现异常。执行代码:

Edytuj = WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='Edytuj pozycję']")))
Edytuj.click()

后触发网站500错误,随后抛出TimeoutException。

按钮HTML代码如下:

<button _ngcontent-dspace-angular-c324="" class="btn btn-dark btn-sm" title="Edytuj pozycję" aria-label="Edytuj pozycję"><i _ngcontent-dspace-angular-c324="" class="fa-fw fa-pencil-alt fas"></i></button>

已尝试CSS选择器和XPath定位按钮均失败;因旁边存在相同类名的按钮,无法通过类名定位。

解决思路
  • 精准定位元素:
    结合按钮的标题和内部图标元素缩小定位范围,确保唯一性:

    • XPath写法:
      //button[@title='Edytuj pozycję' and .//i[@class='fa-fw fa-pencil-alt fas']]
      
    • 或通过图标找父按钮:
      //i[@class='fa-fw fa-pencil-alt fas']/parent::button
      
    • CSS选择器(需Chrome 101+支持):
      button[title='Edytuj pozycję']:has(i.fa-pencil-alt)
      
  • 换用点击方式规避服务器异常:
    网站500错误可能是原生点击触发了未处理的后端逻辑,或元素事件未完全绑定,可尝试:

    1. 模拟鼠标动作点击:
      from selenium.webdriver.common.action_chains import ActionChains
      
      btn = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.XPATH, "//button[@title='Edytuj pozycję']")))
      ActionChains(self.driver).move_to_element(btn).click().perform()
      
    2. 执行JavaScript强制点击:
      btn = WebDriverWait(self.driver, 20).until(EC.presence_of_element_located((By.XPATH, "//button[@title='Edytuj pozycję']")))
      self.driver.execute_script("arguments[0].click();", btn)
      
  • 确保页面完全就绪:
    点击前等待页面加载完成,避免AJAX请求未结束时操作:

    WebDriverWait(self.driver, 20).until(lambda d: d.execute_script('return document.readyState') == 'complete')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:48:22