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

EC2实例运行Selenium爬取Google Play时崩溃问题求助

问题分析与解决方案

可能原因

  • 浏览器进程泄漏:每次脚本执行后未彻底关闭Firefox和Geckodriver进程,导致进程持续堆积,占用CPU和内存资源,多次运行后资源耗尽引发实例崩溃。
  • Google Play反爬限制:重复请求触发反爬机制,页面加载被拦截或卡住,驱动长时间等待导致CPU飙升,最终超时。
  • 等待逻辑冗余/超时设置不合理:重复的等待条件(如同时等待body元素和document.readyState)、过长的等待时间,导致驱动持续占用资源;页面加载超时设置过短但后续等待时间过长,加剧资源消耗。
  • 浏览器/驱动版本潜在bug:当前使用的Firefox、Geckodriver版本可能存在内存泄漏的已知问题,多次运行后累积引发崩溃。

对应解决方案

1. 彻底清理浏览器进程

每次脚本执行完毕,务必调用driver.quit()而非driver.close(),并通过try-finally确保即使报错也能关闭进程:

try:
    # 你的爬取逻辑代码
    driver.set_page_load_timeout(10)
    driver.get(url)
    # ... 后续操作
finally:
    # 确保驱动和浏览器进程被彻底关闭
    if 'driver' in locals():
        driver.quit()

还可以在脚本启动前清理残留进程(Linux环境):

pkill -f firefox
pkill -f geckodriver

2. 规避反爬机制

  • 延长随机等待时间至3-10秒,增大随机范围,模拟真实用户行为:
    time.sleep(random.uniform(3, 10))
    
  • 每次请求更换User-Agent:
    from selenium.webdriver.firefox.options import Options
    
    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Safari/605.1.15"
    ]
    options = Options()
    options.add_argument(f"user-agent={random.choice(user_agents)}")
    driver = webdriver.Firefox(options=options)
    
  • 使用代理IP分散请求来源,避免单一IP被限制。

3. 优化超时与等待逻辑

  • 移除冗余等待条件,保留document.readyState的等待即可:
    wait = WebDriverWait(driver, 30)  # 缩短等待时间至30秒
    wait.until(lambda driver: driver.execute_script("return document.readyState") == "complete")
    
  • 页面加载超时后强制停止加载,避免驱动持续等待:
    try:
        driver.set_page_load_timeout(15)
        driver.get(url)
    except TimeoutException:
        driver.execute_script("window.stop();")  # 强制终止页面加载
    

4. 升级组件版本

尝试将Firefox、Geckodriver升级至最新稳定版,修复已知的内存泄漏或兼容性问题,确保版本匹配。

额外优化建议

  • 使用Firefox无头模式运行,大幅降低资源占用:
    options = Options()
    options.add_argument("--headless")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")  # EC2环境下需添加此参数
    driver = webdriver.Firefox(options=options)
    
  • 监控EC2实例的资源使用情况,通过top、htop命令查看进程残留和CPU/内存占用,定位资源消耗点。
  • 若非必须渲染JavaScript,改用requests配合BeautifulSoup爬取静态数据,替代资源消耗大的Selenium。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:52:15