简体   繁体   中英

I keep getting a NoSuchElementException in selenium even though the element DOES exist

This is my first scraping project using selenium. I'm trying to download a couple of reddit videos saved in a list using this website .

As you can see, it shows an input tag where I need to enter the url of the video or gif then go to the download page. That input tag has a class name form-control form-control-lg form-control-alternative . So when I try getting that element so I can fill it with a link from a list in Python, it shows a selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .form-control form-control-lg form-control-alternative error.

You can check yourselves using the Developer Tools and you'll see that that input tag has that class.

Here's my code:

for gif in gif_list:
    driver.get('https://keepv.id/reddit-video-downloader')
    input_tag = driver.find_element_by_class_name('form-control form-control-lg form-control-alternative')
    input_tag.send_keys(gif)
    go_button = driver.find_element_by_class_name('btn btn-danger')
    go_button.click()
    second_button = driver.find_element_by_class_name('btn btn-danger sheen waggle spin')
    second_button.click()
    WebDriverWait(driver, 5).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, 'row')))
    download_button = driver.find_element_by_class_name('btn btn-lg btn-danger mb-3 shadow vdlbtn')
    download_button.click()
    gif_url = driver.current_url()
    download_gif(gif_url)

find_element_by_class_name() accept single class only use css selector instead.

driver.find_element_by_css_selector(".form-control.form-control-lg.form-control-alternative").send_keys(gif)
driver.find_element_by_css_selector(".btn.btn-danger").click()

Or you can use by_id

driver.find_element_by_id("dlURL").send_keys(gif)
driver.find_element_by_id("dlBTN1").click()

Ideally you should use WebDriverWait () and wait for element_to_be_clickable () and following css selecor

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,".form-control.form-control-lg.form-control-alternative"))).send_keys(gif)

To click go button

WebDriverWait(browser,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,".btn.btn-danger"))).click()

you need to import below libraries

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM