【问题标题】:How get id from dynamic button ? (Python)如何从动态按钮获取 id? (Python)
【发布时间】:2019-10-01 17:15:14
【问题描述】:

我有这个动态变化的 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>

【问题讨论】:

  • 你能发布你的html源代码吗?

标签: python selenium xpath css-selectors webdriverwait


【解决方案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
    

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 这是 html :
    • @FlutterLover 我已经更新了我的帖子,提供了一些您可以尝试的选项。
    • 它工作正常,但它选择了第一个菜单,我的问题是如何将 id 保存为变量,然后我可以点击它并删除它?
    • 在我的示例中,如何将数字 61 保存为 id,然后单击 //*[@id="/api/services/id_ellipsis"] ?
    • @FlutterLover 您将无法通过它的确切 ID 第一次找到该元素,因为它是动态的,如您所说。但是,您可以使用部分 ID 找到元素(例如我发布的示例),然后您可以调用 get_attribute("id") 来访问这样的 ID。我用代码更新了我的示例来做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多