DEV Community

Gregary Boyles
Gregary Boyles

Posted on

Python Selenium select an element via aria-label

I have this element in a web page:


 aria-placeholder="What's on your mind?" aria-label="What's on your mind?" class="xzsf02u x1a2a7pz x1n2onr6 x14wi4xw x9f619 x1lliihq x5yr21d xh8yej3 notranslate" contenteditable="true" role="textbox" spellcheck="true" tabindex="0" data-lexical-editor="true" style="user-select: text; white-space: pre-wrap; word-break: break-word; font-size: 24px;"><p class="xdj266r x11i5rnm xat24cr x1mh8g0r x16tdsg8"><br></p></div>

Enter fullscreen mode Exit fullscreen mode

I am trying to select this element via this code:



def DoGetTextField(browserChrome):
    TextField = None
    arrayAriaLabels = ["Whats on your mind?", "Write something"]
    nWaitSeconds = 5
    for nI in range(0, len(arrayAriaLabels)):
        Wait = WebDriverWait(browserChrome, nWaitSeconds)
        strSelectorString = "[aria-label='" + arrayAriaLabels[nI] + "']"
        TextField = Wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, strSelectorString)))
        Wait = WebDriverWait(browserChrome, nWaitSeconds)
        TextField = Wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, strSelectorString)))
        if TextField is not None:
            break

    return TextField



Enter fullscreen mode Exit fullscreen mode

But that damn single quote in the aria-label is screwing me up.
aria-label="What's on your mind?"

If I leave that single quote out then I get a timeout exception - expected.

But if I include the single quote as ', '' or \' then I get an invalid or illegal selector exception.

How do I resolve it?

Top comments (0)