【问题标题】:Selenium find element where ID attribute begin with unique characters and ends with random charactersSelenium 查找 ID 属性以唯一字符开头并以随机字符结尾的元素
【发布时间】:2021-12-25 04:44:25
【问题描述】:

这是我的按钮在 HTML 中的代码:

<button type="submit" class="btn btn-secondary" id="single_button618eda460b64617" title="">Re-attempt quiz</button>

我为许多其他组件定义的类和id 总是以single_button 开头。

但结尾是随机字符。并且是唯一以这个前缀开头的。

我如何使用button=driver.find_element_by_id(),但对于第一个single_button

【问题讨论】:

  • driver.find_element_by_xpath("//button[contains(@id, 'single_button')]")

标签: python selenium xpath css-selectors findelement


【解决方案1】:

由于元素是唯一的 id 属性前缀以该唯一值开头的元素,您可以使用以下动态Locator Strategies 之一:

  • 使用css_selector

    button = driver.find_element(By.CSS_SELECTOR, "button[id^='single_button']")
    

PS:id^表示,id属性的值以开头。

  • 使用xpath

    button = driver.find_element(By.XPATH, "//button[starts-with(@id, 'single_button')]")
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多