Search code examples
pythonseleniumselenium-webdrivercss-selectorswebdriverwait

Trying to locate an element in a webpage but getting NoSuchElementException


I am trying to get the webdriver to click a button on the site random.org The button is a generator that generates a random integer between 1 and 100. It looks like this:

The generator button

After inspecting the webpage, I found the corresponding element on the webpage looks something like this:

The HTML skeleton

It is inside an iframe and someone suggested that I should first switch over to that iframe to locate the element, so I incorporated that in my code but I am constantly getting NoSuchElementException error. I have attached my code and the error measage below for your reference. I can't understand why it cannot locate the button element despite referencing the ID, which is supposed to unique in the entire document.

The code:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Edge()

driver.get("https://www.random.org/")

driver.implicitly_wait(15)

driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))

button = driver.find_element(By.CSS_SELECTOR, "input[id='hnbzsqjufzxezy-button']")

button.click()

The error message:

The error message


Solution

  • Make sure that there are no more Iframes on the page. If there are a few an not only one do this:

    iframes = driver.find_elements(By.CSS, 'iframe')
    // try switching to each iframe:
    driver.switch_to.frame(iframes[0])
    driver.switch_to.frame(iframes[1])
    

    You can't find the button because its name contain random letters. Every time you will refresh the page you can see that the name value will change. So, do this:

    button = driver.findElement(By.CSS, 'input[type="button"][value="Generate"]')
    button.click()