9

I'm using selenium with python,now I want to locate an element by part of its id name,what can I do?

For example,now I've already located a item by id name coption5 :

sixth_item = driver.find_element_by_id("coption5")

Is there anyway I can locate this element only by using coption?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

24

To find the element which you have located with:

sixth_item = driver.find_element_by_id("coption5")

To locate this element only by using coption you can use can use either of the following Locator Strategies:

  • Using XPATH and starts-with():

    sixth_item = driver.find_element_by_xpath("//*[starts-with(@id, 'coption')]")
    
  • Using XPATH and contains():

    sixth_item = driver.find_element_by_xpath("//*[contains(@id, 'coption')]")
    
  • Using CSS_SELECTOR and ^ (wildcard of starts-with):

    sixth_item = driver.find_element_by_css_selector("[id^='coption']")
    
  • Using CSS_SELECTOR and * (wildcard of contains):

    sixth_item = driver.find_element_by_css_selector("[id*='coption']")
    

Reference

You can find a detailed discussion on dynamic CssSelectors in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • 1
    Thank you so much for your reply,but in my situation it doesn't work now.I'll keep trying! – William Jan 08 '20 at 20:38
  • Sir can you help me with this one https://stackoverflow.com/questions/59653599/how-to-locate-element-by-class-name-and-specific-attribute-name-at-the-same-time – William Jan 08 '20 at 20:50
  • 1
    It is so useful!Thank you so much! – William Jan 09 '20 at 21:56