You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium使用presence_of_all_elements_located无法获取完整元素列表

问题解决:Wolt菜单爬取仅获取9个条目

问题原因

页面采用懒加载机制:初始仅渲染可视区域的菜品,未滚动到的内容不会加载到DOM中。presence_of_all_elements_located只会等待当前已加载的元素,无法触发滚动加载更多菜品。

解决方案

模拟页面滚动触发懒加载,直到所有菜品加载完成。修改后的代码如下:

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
import time

path = "/Users/ruhanamirza/Downloads/chromedriver"
driver = webdriver.Chrome(path)
driver.get('https://wolt.com/az/aze/baku/venue/gurmania-winter-park')

try:
    # 等待初始菜品元素加载
    WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, "MenuItem-module_content__mNrbB"))
    )
    
    last_item_count = 0
    while True:
        # 获取当前已加载的菜品元素列表
        current_items = driver.find_elements(By.CLASS_NAME, "MenuItem-module_content__mNrbB")
        current_count = len(current_items)
        
        # 元素数量不再变化时,停止滚动
        if current_count == last_item_count:
            break
        
        last_item_count = current_count
        
        # 滚动到页面底部,触发懒加载
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # 等待新元素加载,可根据页面速度调整等待时间
        time.sleep(2)
    
    # 遍历所有菜品并打印名称
    for item in current_items:
        name = item.find_element(By.CLASS_NAME, "MenuItem-module_name__iqvnU")
        print(name.text)

finally:
    driver.quit()

额外说明

  • 若页面存在隐私政策弹窗,需先添加代码关闭弹窗,否则会影响滚动和元素定位
  • time.sleep(2)可按需调整,也可替换为显式等待(等待新元素出现),提升稳定性

内容的提问来源于stack exchange,提问作者Masail Guliyev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:30:54