Nikhil
Nikhil

Reputation: 81

How to include regex in the css selector in python selenium

I am trying the extract the text by using the CSS selector. as variables are dynamic in nature they are continuously updating.

#profileCard-ACoAABI4A30BKLei-DtaS6B6vQo-3ejw-nzI1W8-EDUCATION-en-US 

this is a CSS selector

driver.find_element_by_css_selector('#profileCard-ACoAABI4A30BKLei-DtaS6B6vQo-3ejw-nzI1W8-EDUCATION-en-US').text

x_path = //*[@id="profileCard-ACoAABI4A30BKLei-DtaS6B6vQo-3ejw-nzI1W8-EDUCATION-en-US"]
# here i tried to apply the regex
driver.find_element_by_xpath("//*[ends-with(@id,'EDUCATION-en-US')]") 

But I'm getting an error as 'InvalidSelectorException'.
Is there any way to get the data without error?

'ACoAABI4A30BKLei-DtaS6B6vQo-3ejw-nzI1W8' this path will be continuously updating. '#profileCard', 'EDUCATION-en-US' there will be no change in this

Any help or lead to solve the issue would be very helpful. Thanks in advance

Upvotes: 2

Views: 1458

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

For value of id attributes like:

#profileCard-ACoAABI4A30BKLei-DtaS6B6vQo-3ejw-nzI1W8-EDUCATION-en-US

xpath doesn't supports ends-with(). Instead you can use either of the following options:

  • Using xpath:

    driver.find_element(By.XPATH, "//*[starts-with(@id, 'profileCard') and contains(@id, 'EDUCATION-en-US')]").text
    
  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "[id^='profileCard'][id$='EDUCATION-en-US']").text
    

Upvotes: 0

Prophet
Prophet

Reputation: 33361

This should do what you are looking for:

driver.find_element_by_css_selector('[id^="profileCard-"][id$="-EDUCATION-en-US"]').text

The ^ denotes what the id should begin with.

The $ denotes what the id should end with.

Upvotes: 4

Related Questions