Home > Software design >  Message: invalid selector: An invalid or illegal selector was specified error using Selenium Python
Message: invalid selector: An invalid or illegal selector was specified error using Selenium Python

Time:05-03

I'm trying to click on this element:

<td role="gridcell"  tabindex="0" data-mat-row="0" data-mat-col="1" aria-label="May 2, 2022" aria-selected="true" style="width: 14.2857%; padding-top: 7.14286%; padding-bottom: 7.14286%;"><div > 2 </div><div ></div></td>

To do so, I'd like to select it via the element's aria-label (May 2, 2022). So I have a variable that contains the string "May 2, 2022" (the string is called theElement), and I plug it into a find_element function.

Why is this code snippet giving me the:

Message: invalid selector: An invalid or illegal selector was specified

error?

Code trials:

driver.find_element(by=By.CSS_SELECTOR, value="[aria-label=" theElement "]")

CodePudding user response:

To locate the <td> element through the value of the aria-label attribute i.e. May 2, 2022 you can use either of the following Locator Strategies:

  • Using css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "td[aria-label='May 2, 2022']")
    
  • Using xpath:

    element = driver.find_element(By.XPATH, "//td[@aria-label='May 2, 2022']")
    
  • Related