How to get selectors with dynamic part inside using Selenium with Python?

后端 未结 2 958
忘了有多久
忘了有多久 2020-12-04 03:30

My application has a lot of selectors that have a dynamic ID inside. When that dynamic ID is at the end of the selector, I use [id^=\'staticPart\'] inside of ev

相关标签:
2条回答
  • 2020-12-04 03:53

    To identify an element with dynamic id e.g. #tab-t0-1 where 0 is a dynamic number and everything else is static you can use cssSelector with the following wildcards :

    • ^ : To indicate an attribute value starts with

    • $ : To indicate an attribute value ends with

    So the most granular locator would include the strategy to lookout for the initial letters i.e. tab-t and the ending letters i.e. -1 and should be :

    [id^='tab-t'][id$='-1']
    

    Reference

    You can find a detailed discussion on dynamic CssSelectors in:

    • How to find element by part of its id name in selenium with python
    0 讨论(0)
  • You can, at the very least, combine both "starts with" and "ends with" selectors:

    [id^='tab-'][id$='-1']
    

    In general, though, depending on the selectivity of the id values like these, the [id$='-1'] part might not be significant or distinguishing and something more straightforward could be enough:

    [id^=tab]
    

    This is, of course, specific to the particular markup you are dealing with.

    0 讨论(0)
提交回复
热议问题