【问题标题】:Locating an element with dynamic ID using Selenium and Python使用 Selenium 和 Python 定位具有动态 ID 的元素
【发布时间】:2021-12-30 10:43:02
【问题描述】:

我需要通过 ID“start-ads”找到一个元素,但末尾的数字每次都会改变。是否可以不按整个 ID,而仅按其部分搜索元素?

Full element id: <div id="start-ads-202308">

【问题讨论】:

    标签: python selenium selenium-webdriver xpath css-selectors


    【解决方案1】:

    您可以使用 find_element_by_css_selector 并使用使用前缀匹配的 CSS 选择器

    driver.find_element_by_css_selector("div[id^='start-ads-']")
    

    【讨论】:

      【解决方案2】:

      识别以下元素:

      <div id="start-ads-202308">
      

      考虑到 id 属性值的静态部分,您可以使用以下任一Locator Strategies

      • 使用css_selector

        element = driver.find_element(By.CSS_SELECTOR, "div[id^='start-ads-']")
        

        其中 ^ 表示开始于

      • 使用xpath

        element = driver.find_element(By.XPATH, "//div[starts-with(@id, 'start-ads-')]")
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-29
        • 1970-01-01
        • 2020-06-17
        相关资源
        最近更新 更多