Jossy
Jossy

Reputation: 1007

Why am I getting NoSuchElementException for find_element_by_id?

When trying to execute the following code:

driver = webdriver.Firefox()
driver.get("https://www.flashscore.co.uk/tennis/")
cookie_button = driver.find_element_by_id("onetrust-accept-btn-handler")
cookie_button.click()

I'm getting this exception:

Exception has occurred: NoSuchElementException
Message: Unable to locate element: [id="onetrust-accept-btn-handler"]

When I look through the HTML on the page I can see the following line which is the button I want to click on:

<button id="onetrust-accept-btn-handler">I Accept</button>

Picture of site below:

enter image description here

Picture of the HTML "Inspector":

enter image description here

(apologies not sure how to copy this as text)

Why can't Selenium locate the element?

Upvotes: 0

Views: 62

Answers (1)

cruisepandey
cruisepandey

Reputation: 29362

You need to use ExplicitWait

The below code works for me :

executablePath = r'C:\geckodriver.exe'
options = webdriver.FirefoxOptions()
driver = webdriver.Firefox(executable_path = executablePath, options=options)
driver.maximize_window()
driver.get("https://www.flashscore.co.uk/tennis/")
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@id='onetrust-accept-btn-handler']"))).click()
print('Operation successful')

Imports :

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Upvotes: 1

Related Questions