Python Selenium - select an element via aria-label

I have this element in a web page:

<div 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>

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

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?

What will this strSelectorString contain when you use it?

I’m not sure what syntax selenium accepts but the issue is that your can’t use single quotes to define a string that contains single quotes. You could use double quotes or you could escape the inner single quote.

It turned out to be how I was using the quotes.

When I swapped the ’ " for \" " then it worked.

[aria-label=\“What’s on your mind\”]

One thing I don’t like about Python and Javascript…the use of quotes in strings can get confusing.

It is simpler with C - you only use " for strings and nothing else.

1 Like

It can be convenient to avoid escapes occassionally:

a = 'bob said "hi"'
b = "bob's burgers"

vs.

a = "bob said \"hi\""
b = 'bob\'s burgers'

Having said that. I’m inclined to agree and like to stick to using " for all string literals. Escapes aren’t that bad, worth getting used to :slight_smile: