nbboarder88
nbboarder88

Reputation: 29

How to find element (using ID) beginning "x" with and ends with "y" .... "and" logic

I'm trying to have my code click IDs progressively using lambda/function. The beginning ID string is fixed, i.e. "abc" and there is a middle section that is variable and ending of ID string is also known/progressive, i.e. "1, 2, 3, 4, etc."...

Is there a way to incorporate this "and" logic with find_element(By.ID) or another way?

Feeding the code the exact ID works obviously and I can have the code select the first instance of the ID using CSS Selector [id^="abc"] (begins with) but I have not been successful getting the code to progress through the id chain/ incorporating ends with logic like [id$="2"] etc

I've been trying degrees of the following with CSS selector with no luck:

driver.find_element(By.CSS_SELECTOR, '[id^="abc"]' and '[id$="2"]').click()

With this error:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

Upvotes: 0

Views: 514

Answers (1)

sound wave
sound wave

Reputation: 3547

You were almost there

driver.find_element(By.CSS_SELECTOR, "[id^='abc'][id$='2']")

While in xpath is a little bit harder

i = 2
starts_with = "starts-with(@id, 'abc')"
ends_with = f"substring(@id, string-length(@id) - string-length('{i}')+1) = '{i}'"
driver.find_element(By.XPATH, f"//div[{starts_with} and {ends_with}]")

Upvotes: 1

Related Questions