【问题标题】:selenium.common.exceptions.TimeoutException: Message: Error trying to print out titles of showsselenium.common.exceptions.TimeoutException:消息:尝试打印节目标题时出错
【发布时间】:2021-10-15 23:34:42
【问题描述】:

我在运行这个简短的脚本时遇到了您在上面看到的错误:

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()

对于这个错误,我看到了不同的答案,但它们都太针对具体情况了,所以我决定自己发帖。如果您有任何方法可以解决此错误,请告诉我。提前致谢!

编辑:我尝试简单地将超时时间从 10 增加到 30,依此类推。但是出现同样的错误

【问题讨论】:

    标签: selenium xpath css-selectors webdriverwait timeoutexception


    【解决方案1】:

    您使用了错误的定位器。
    由于您通过多个类名定位元素,因此您应该使用 CSS_SELECTOR,而不是 By.CLASS_NAME
    此外,您应该等待元素可见性,而不仅仅是存在。
    此外,要搜索元素内的元素,建议使用以点 . 开头的 XPath,就像我在此处使用的那样。
    看看这是否适合你:

    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()
    

    【讨论】:

    • 你是真正的传奇!谢谢,它成功了!你能解释一下,为什么你使用 xpath 而不是 class_name 吗?
    • 如果有多个类名,您可以使用 XPath 或 CSS 选择器,正如我在答案中提到的那样。此外,为了在元素内部搜索,您应该使用我描述的 XPath。
    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多