Search code examples
seleniumxpathcss-selectorswebdriverwaittimeoutexception

selenium.common.exceptions.TimeoutException: Message: Error trying to print out titles of shows


I got the error you can see above while running this short script:

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

url ='https://animelon.com/'

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get(url)

try:
    section = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, 'row ng-show-toggle-slidedown series-content-container'))
    )

    anime = section.find_elements_by_class_name('col-lg-3 col-md-4 col-sm-6 col-xs-12 mini-previews ng-scope')

    for show in anime:
        header = show.find_element_by_class_name('anime-name ng-binding')
        print(header.text)

finally:
    driver.quit()

I've seen different answers to this error but they are all too case-specific so I decided to make my own post. Please let me know if you have any way to fix this error. Thanks in advance!

Edit: I've tried to simply increase the timeout from 10 to 30 and so on. But the same error appears


Solution

  • You are using wrong locator.
    Since you locating the element by multiple class names you should use CSS_SELECTOR, not By.CLASS_NAME
    Also, you should wait for elements visibility, not just presence.
    Also, to search for elements inside element it's recommended to use XPath starting with dot . as I used here.
    See if this will work for you:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    url ='https://animelon.com/'
    
    PATH = 'C:\Program Files (x86)\chromedriver.exe'
    driver = webdriver.Chrome(PATH)
    driver.get(url)
    
    try:
        section = WebDriverWait(driver, 10).until(
            EC.visibility_of_element_located((By.CSS_SELECTOR, '.row.ng-show-toggle-slidedown.series-content-container'))
        )
    
        anime = section.find_elements_by_xpath('.//*[@class="col-lg-3 col-md-4 col-sm-6 col-xs-12 mini-previews ng-scope"]')
    
        for show in anime:
            header = show.find_element_by_xpath('.//*[@class="anime-name ng-binding"]')
            print(header.text)
    
    finally:
        driver.quit()