2

I need to find an element by ID "start-ads", but the numbers at the end change every time. Is it possible to search for an element not by the whole ID, but only by its part?

Full element id: <div id="start-ads-202308">
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
PECTAPT
  • 21
  • 3

2 Answers2

1

To identify the following element:

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

considering the static part of the value of id attribute you can use either of the following Locator Strategies:

  • Using css_selector:

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

    where ^ denotes starts-with

  • Using xpath:

    element = driver.find_element(By.XPATH, "//div[starts-with(@id, 'start-ads-')]")
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You can use find_element_by_css_selector and use a CSS selector that matches using a prefix

driver.find_element_by_css_selector("div[id^='start-ads-']")
Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50