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

问题描述 投票:-1回答:2

我有一个动态变化的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>
python selenium xpath css-selectors webdriverwait
2个回答
0
投票

如果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")

1
投票

所需的元素是动态元素,因此对于元素上的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
    
© www.soinside.com 2019 - 2024. All rights reserved.