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

使用XPATH定位动态生成Web元素后出现的Bug排查

XPATH定位Web元素的长期运行Bug问题

问题概述

程序启动初期可正常处理数百条从外部文件获取的数据,但当DOM结构疑似发生变化时,会出现Bug,导致Selenium WebDriver定位到程序之前引用过的非目标元素。

Bug演示

有对应的Bug演示视频,可直观看到定位错误的场景。

定位元素的相关代码片段

def diagnosis(self, driver, patient):
    try:
        wait = WebDriverWait(driver,10)
        valid_diagnoses = [dx for dx in patient.diagnosis if dx and len(str(dx)) < 1000 and not re.search(r"\bnan\b",str(dx))]
        xpath_id = [7, 10, 13, 16, 19, 22, 25]
        count = 0
        diagnosis_index = 0

        while count < len(valid_diagnoses)/2:
            wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn.btn-sm.btn-secondary.font-medium.text-sm.text-gray-700"))).click()
            time.sleep(2)
            try:
                diagnosis_field = None
                diagnosis_field = wait.until(EC.visibility_of_element_located((By.XPATH, f'//*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[{xpath_id[count]}]//input[not(@disabled)]')))
                text = valid_diagnoses[diagnosis_index].strip()
                diagnosis_field.send_keys(text)
                wait.until(EC.text_to_be_present_in_element_value((By.XPATH, f'//*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[{xpath_id[count]}]//input[not(@disabled)]'), text))
            except:
                print(f'An error related to the patient\'s diagnosis being entered is occurring. Program will wait 100 seconds, inspect the HTML')
                time.sleep(100)
                patient.dx_issue = True
            diagnosis_index += 2
            count += 1
    except TimeoutError:
        print("Timed out while completing the diagnosis process in Webdriver.py")

被定位的DOM元素情况

  • 诊断1的DOM结构截图:对应的XPATH为 //*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[10]/div[2]/input
  • 诊断2的DOM结构截图:对应的XPATH与诊断1完全相同,为 //*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[10]/div[2]/input

已尝试的解决方案

  • 测试过CSS_SELECTOR及多种XPATH语句,最终选择XPATH更贴合需求
  • 最初使用的XPATH://*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[{xpath_id[count]}]/div[1]/input
  • 修改后的XPATH://*[@id="919e06c4ea7e2a5bb720134d693a8671"]/div[2]/div[1]/div[2]/div/form/div/div/div[{xpath_id[count]}]//input[not(@disabled)],修改后能应对部分未预料的DOM变化,成功处理了数百条数据,但长期运行仍会触发Bug

怀疑方向

怀疑未考虑Selenium WebDriver长时间运行的限制,不清楚程序持续运行多久会出现Bug,尤其是在处理数百条包含独特就诊记录的数据时。

环境信息

  • Google Chrome版本:122.0.6261.95(官方版本,64位)
  • 操作系统:Windows 11 Home
  • Selenium版本:4.15.2

补充说明

已提供对应的HTML页面,用于深入分析DOM结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:14:53