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

使用Selenium爬取Tenor网站GIF仅获取24个的问题排查

Tenor爬取GIF仅能获取24个的问题排查

核心问题分析

Tenor的内容加载机制和普通图片站点不同,你遇到的24个限制大概率是以下几个原因导致:


1. 元素选择器错误

你用的class="Gif "带了尾空格,这很可能是问题根源。Tenor的GIF容器class通常是Gif(无空格),或者随着页面更新已经换成了其他类名(比如grid-item、gif-wrap)。

  • 解决:打开Tenor页面按F12,找到新滚动出来的GIF元素,查看它的真实class名,替换你的选择器。

2. 滚动逻辑未触发内容加载

一次性滚动到底或者滚动后等待时间不足,会导致Tenor没来得及加载新内容就被你抓取了。

  • 优化滚动代码,分段滚动+等待新元素加载:
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.common.by import By
    import time
    
    # 初始化driver后先获取初始GIF数量
    initial_gif_count = len(driver.find_elements(By.CLASS_NAME, "Gif"))
    last_scroll_height = driver.execute_script("return document.body.scrollHeight")
    
    while True:
        # 滚动到当前页面底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # 等待3秒让内容加载,或者用更可靠的等待逻辑
        time.sleep(3)
        # 检查是否有新的GIF加载
        current_gif_count = len(driver.find_elements(By.CLASS_NAME, "Gif"))
        current_scroll_height = driver.execute_script("return document.body.scrollHeight")
        # 如果数量没增加且页面高度不变,说明没有更多内容
        if current_gif_count == initial_gif_count and current_scroll_height == last_scroll_height:
            break
        initial_gif_count = current_gif_count
        last_scroll_height = current_scroll_height
    
  • 更可靠的方式是用WebDriverWait等待元素数量增长:
    while True:
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        try:
            # 等待10秒,直到GIF数量超过之前的计数
            WebDriverWait(driver, 10).until(
                lambda d: len(d.find_elements(By.CLASS_NAME, "Gif")) > initial_gif_count
            )
            initial_gif_count = len(driver.find_elements(By.CLASS_NAME, "Gif"))
        except:
            # 超时则停止,说明无更多内容
            break
    

3. 懒加载未触发真实GIF链接

Tenor用了懒加载,只有当GIF元素进入视口才会加载真实的资源链接,直接抓取可能只拿到占位图或者初始的24个已加载链接。

  • 解决:滚动后可以遍历所有GIF元素,用JavaScript触发每个元素的加载,或者确保每个元素都进入视口:
    gifs = driver.find_elements(By.CLASS_NAME, "Gif")
    for gif in gifs:
        # 将元素滚动到视口内
        driver.execute_script("arguments[0].scrollIntoView();", gif)
        time.sleep(0.5)
    

4. 反爬机制限制

Tenor可能会检测到自动化脚本,限制内容加载量。

  • 解决:添加真实的用户代理:
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
    driver = webdriver.Chrome(options=options)
    
  • 避免快速滚动,增加滚动间隔,模拟真实用户行为。

5. BeautifulSoup抓取时机错误

用BeautifulSoup时,要确保是滚动加载完成后再获取driver.page_source,否则拿到的还是初始页面的源码,自然只有24个GIF。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 06:21:37