Search code examples
pythonselenium-webdriverselenium-chromedriver

How can I fix NoSuchElementException error in python?


This is the HTML of search of virustotal but I'm receiving the below error.

<input type="text" id="searchInput" class="form-control px-3 position-absolute h-100 bg-transparent" autocomplete="off" spellcheck="false" autofocus="" placeholder="URL, IP address, domain, or file hash">

Error:

search = driver.find_element(By.ID, "searchInput")
NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[id="searchInput"]"}

My code:

PATH = r"D:\VT Automation\chromedriver.exe"
service = Service(executable_path='./chromedriver.exe')

# Set up Chrome options
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(service=service, options=options)

driver.get("https://www.virustotal.com/gui/home/search")
time.sleep(5)

# Locate the search input element
search = driver.find_element(By.ID, "searchInput")

search.send_keys("759b1fcbdf4ad54bb8adc2c060df8ab5")
search.send_keys(Keys.RETURN)

# Wait for the result element to be present
try:
    result = WebDriverWait(driver, 15).until(
        EC.presence_of_element_located((By.CLASS_NAME, "positives"))
    )
    print(result.text)
except Exception as e:
    print(f"An error occurred: {e}")
finally:
    driver.quit()

Solution

  • The <input> element is within multiple shadow-root elements. In such cases, selenium can't directly interact with the desired element. You can interact with desired element using Javascript as in the below code.

    enter image description here

    Code:

    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("https://www.virustotal.com/gui/home/search")
    driver.maximize_window()
    wait = WebDriverWait(driver, 15)
    wait.until(EC.element_to_be_clickable((driver.execute_script("return document.querySelector('home-view').shadowRoot.querySelector('vt-ui-search-bar').shadowRoot.querySelector('input#searchInput')")))).send_keys("test")
    driver.quit()
    

    Result:

    enter image description here