【问题标题】:Python Selenium: get_elements method does not get li items in ulPython Selenium:get_elements 方法无法获取 ul 中的 li 项
【发布时间】:2022-01-15 04:03:20
【问题描述】:

我正在尝试在 ul 中获取 li 项目。这是我的代码:

driver.get('https://migroskurumsal.com/magazalarimiz/')

try:
    select = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, 'stores'))
    )
    print('Dropdown is ready!')
except TimeoutException:
    print('Took too much time!')

select = Select(driver.find_element(By.ID,'stores'))

select.select_by_value('2')

try:
    shopList = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "shopList"))
    )
    print('Shoplist is ready!')
except TimeoutException:
    print('Took too much time!')
    driver.quit()


print(shopList.get_attribute("class"))


li_items = shopList.find_elements(By.TAG_NAME,'li')

print(len(li_items))

我成功找到了 id=shopList 的 ul 元素。然后我尝试使用 find_elements(By.TAG_NAME) 获取 ul 下的所有 li 元素。我还尝试了 find_elements(By.CLASS_NAME),但是 len(li_items) 始终为 0。我请求您的帮助。谢谢。

【问题讨论】:

    标签: python html selenium


    【解决方案1】:

    在您的情况下,等到EC.presence_of_element_located((By.ID, "shopList")) 不会成功,因为这个ul 已经在页面上,即使在选择过滤器之前,它也是空的。相反,您可以等到li 子元素可见。

    例子:

    driver.get('https://migroskurumsal.com/magazalarimiz/')
    
    try:
        select = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.ID, 'stores'))
        )
        print('Dropdown is ready!')
    except TimeoutException:
        print('Took too much time!')
    
    select = Select(driver.find_element(By.ID, 'stores'))
    
    select.select_by_value('2')
    shopList = driver.find_element(By.ID, "shopList")
    try:
        WebDriverWait(driver, 10).until(
            EC.visibility_of_all_elements_located((By.XPATH, "//ul[@id='shopList']/li"))
        )
        print('Shoplist is ready!')
    except TimeoutException:
        print('Took too much time!')
        driver.quit()
    
    print(shopList.get_attribute("class"))
    
    li_items = shopList.find_elements(By.TAG_NAME, 'li')
    
    print(len(li_items))
    

    输出结果:

    Dropdown is ready!
    Shoplist is ready!
    shop-list list-unstyled
    601
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2022-07-16
    • 1970-01-01
    • 2022-12-05
    • 2015-02-15
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多