Selenium Webdriver not able to locate and click button

Question:

I am trying to create a scraper, and for accessing the page I need to click on the Accept Cookies button.
The HTML referring to the button is:

<div class="qc-cmp2-summary-buttons">
    <button mode="secondary" size="large" class=" css-1hy2vtq">
        <span>MORE OPTIONS</span>
    </button><button mode="primary" size="large" class=" css-47sehv">
        <span>AGREE</span></button></div>

The button I want to click is the second one, named "AGREE".

I tried:

driver.find_element(By.CLASS_NAME, " css-47sehv").click()

and I get error
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified

Asked By: Elena Popescu

||

Answers:

Try to use By.CSS_SELECTOR. Find element and copy its selector

Answered By: JustDarkForce

The error you received caused by a space before the class name value.
Spaces between class names are used to separate between multiple class names.
So, to use this specific class name you could try this (without the space):

driver.find_element(By.CLASS_NAME, "css-47sehv").click()

But css-47sehv seems to be a dynamically generated class name so I’d advice to use more fixed attribute for locating that element.
Try this locator instead:

driver.find_element(By.XPATH, "//button[contains(.,'AGREE')]").click()

To give you better answer we need to see that web page and all your Selenium code

Answered By: Prophet