3

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?

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
William
  • 1,666
  • 2
  • 24
  • 50
  • Use XPATH's "contains" method: https://www.guru99.com/xpath-selenium.html#6 – pcalkins Jan 07 '20 at 22:44
  • Use css: `[id^="coption"]` – pguardiario Jan 08 '20 at 02:14
  • @Guy This question is all about locators _Xpath_ and _Css_, any reason why you want to hide the question from _Xpath_ and _Css_ contributors removing those tags? – DebanjanB Jan 08 '20 at 06:45
  • @DebanjanB Using xpath and css_selector is the solution, not the question. – Guy Jan 08 '20 at 07:20
  • @Guy So what do you feel the question was all about :) Does Selenium have any other way other then _Css_ and _Xpath_ – DebanjanB Jan 08 '20 at 07:23
  • @DebanjanB yes, it has https://selenium-python.readthedocs.io/locating-elements.html – Guy Jan 08 '20 at 07:26
  • @Guy I'm sorry, I'm not getting your logic here. Anyway, please try to assist the _New contributors_ rather then reducing the visibility of the questions asked. – DebanjanB Jan 08 '20 at 07:32
  • Thank you so much for your reply,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 Answers1

12

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:

DebanjanB
  • 118,661
  • 30
  • 168
  • 217
  • 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