如何从动态按钮获取 id? (Python)

How get id from dynamic button ? (Python)

我有一个动态变化的 xpath 元素,我喜欢点击它,我该怎么做?

//*[@id="/api/services/61_ellipsis"]

按钮 HTML 是:

<button type="button" class="v-btn v-btn--flat v-btn--icon v-btn--round theme--light v-size--default" id="/api/services/33_ellipsis">
    <span class="v-btn__content">
        <i aria-hidden="true" class="v-icon notranslate mdi mdi-dots-vertical theme--light">
        </i>
    </span>
</button>

如果 ID 动态变化,您不能使用确切的 ID 来获取元素,但 contains 查询可能有效

查询ID中包含api/services的任意元素:

//*[contains(@id, 'api/services')]

在没有任何ID信息的按钮上查询。具有内部 spani 元素:

//button[span/i]

查询 ID 中包含 api/services 且还具有内部 spani 元素的按钮元素:

//button[span/i and contains(@id, 'api/services')]

要保存 ID,您要查找元素然后获取其 ID 属性:

buttonId = driver.find_element_by_xpath("//button[span/i and contains(@id, 'api/services')]").get_attribute("id")

所需的元素是一个动态元素,因此对于 click() 元素,您必须为 element_to_be_clickable() 引入 WebDriverWait,您可以使用以下任一方法以下解决方案:

  • 使用CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.v-btn.v-btn--flat.v-btn--icon.v-btn--round.theme--light.v-size--default[id^='/api/services/'] > span.v-btn__content > i.v-icon.notranslate.mdi.mdi-dots-vertical.theme--light"))).click()
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='v-btn v-btn--flat v-btn--icon v-btn--round theme--light v-size--default' and starts-with(@id, '/api/services/')]/span[@class='v-btn__content']/i[@class='v-icon notranslate mdi mdi-dots-vertical theme--light']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC