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

Ubuntu 20.04 VPS部署Django+SeleniumGrid爬虫应用异常求助

问题分析与解决/测试方案

问题背景

已将网页爬虫集成至Django,本地Windows环境通过webdriver.remote()搭配Selenium Grid运行正常。部署到DigitalOcean Ubuntu 20.04 VPS(使用gunicorn+nginx)后,Django基础功能可正常访问,但调用爬虫时无任何响应。相关初始化代码如下:

def chromedriver_setup():
    user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
    # proxies = proxies = [{"_id":"62cd1bf852694154bb14f2e7","ip":"178.32.148.251","anonymityLevel":"elite","asn":"AS16276","city":"Gravelines","country":"FR","created_at":"2022-07-12T07:00:08.515Z","google":True,"isp":"OVH SAS","lastChecked":1657848951,"latency":5.13,"org":"MICHOTTE Maxime","port":"8080","protocols":["socks4"],  "speed":37,"updated_at":"2022-07-15T01:35:51.569Z"  },{"_id":"60d613cdce5b3bb0e932edce","ip":"64.227.62.123","port":"80","anonymityLevel":"elite","asn":"AS14061","city":"Santa Clara","country":"US","created_at":"2021-06-25T17:35:09.953Z","google":True,  "isp":"DigitalOcean, LLC","lastChecked":1657847332,"latency":153,"org":"DigitalOcean, LLC","protocols":["http"],  "speed":306,"updated_at":"2022-07-15T01:08:52.862Z"  ,"upTime":99.98473981382573,"upTimeSuccessCount":6552,"upTimeTryCount":6553}]
    # random_ip = random.choice(proxies)
    # PROXY = str(random_ip["ip"] + ":" + random_ip["port"])
    option = webdriver.ChromeOptions()
    option.add_argument("--headless")
    option.add_argument(f'user-agent={user_agent}')

    option.add_argument("--window-size=1920,1080")
    option.add_argument("--start-maximized")
    option.add_argument("--disable-gpu")
    # # option.add_argument('--proxy-server=%s' % PROXY)
    option.add_experimental_option("excludeSwitches", ["enable-automation"])
    option.add_experimental_option('useAutomationExtension', False)
    option.add_argument("--disable-blink-features=AutomationControlled")
    option.add_experimental_option("detach", True)
    print("chrome driver setup passed")
    driver = webdriver.Remote(
        command_executor='192.168.72.1:4444',
        desired_capabilities = DesiredCapabilities.CHROME,
        options=option,
    )
    return driver

解决与测试步骤

1. 检查Selenium Grid的连接可达性

代码中command_executor使用的是局域网IP192.168.72.1:4444,VPS无法直接访问本地局域网地址:

  • 如果Selenium Grid部署在本地:需要配置路由器端口转发,将4444端口映射到本地Grid所在机器,同时将command_executor改为你的公网IP+端口;
  • 如果Selenium Grid部署在VPS:确认Grid服务正常运行,在VPS终端执行以下命令测试连接:
    curl http://192.168.72.1:4444/wd/hub/status
    
    注意:部分Grid版本需要加上/wd/hub路径,若原代码未加,需补充。

2. 验证VPS上Chrome环境(若Grid部署在VPS)

确保VPS安装了对应版本的Chrome和ChromeDriver,版本需严格匹配:

# 查看Chrome版本
google-chrome --version
# 查看ChromeDriver版本
chromedriver --version

若版本不匹配,重新下载对应版本的ChromeDriver,或升级/降级Chrome。

3. 查看日志定位异常

爬虫无响应通常是因为有错误未输出,需查看关键日志:

  • Gunicorn日志(若用systemd管理):
    journalctl -u gunicorn.service -f
    
  • Django日志:检查项目中settings.py配置的日志文件,查看调用爬虫时的报错信息。

4. 调整ChromeOptions参数适配Linux环境

Linux环境下需补充必要参数,同时移除Remote模式不需要的设置:

  • 添加--no-sandbox:解决Gunicorn运行用户无沙箱权限的问题;
  • 添加--disable-dev-shm-usage:避免Linux下共享内存不足的问题;
  • 注释--detach:Remote模式下此参数无效,可能导致资源占用异常。

修改后的参数示例:

option = webdriver.ChromeOptions()
option.add_argument("--headless")
option.add_argument(f'user-agent={user_agent}')
option.add_argument("--window-size=1920,1080")
option.add_argument("--disable-gpu")
option.add_argument("--no-sandbox")  # 新增
option.add_argument("--disable-dev-shm-usage")  # 新增
option.add_experimental_option("excludeSwitches", ["enable-automation"])
option.add_experimental_option('useAutomationExtension', False)
option.add_argument("--disable-blink-features=AutomationControlled")
# option.add_experimental_option("detach", True)  # 注释

5. 独立测试爬虫代码

在VPS上单独运行测试脚本,直接定位初始化driver的问题:

from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

def test_driver():
    user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'
    option = webdriver.ChromeOptions()
    option.add_argument("--headless")
    option.add_argument(f'user-agent={user_agent}')
    option.add_argument("--window-size=1920,1080")
    option.add_argument("--disable-gpu")
    option.add_argument("--no-sandbox")
    option.add_argument("--disable-dev-shm-usage")
    option.add_experimental_option("excludeSwitches", ["enable-automation"])
    option.add_experimental_option('useAutomationExtension', False)
    option.add_argument("--disable-blink-features=AutomationControlled")
    
    print("Starting driver setup...")
    try:
        driver = webdriver.Remote(
            command_executor='http://<你的Grid地址>:4444/wd/hub',  # 替换为实际地址
            desired_capabilities=DesiredCapabilities.CHROME,
            options=option,
        )
        print("Driver initialized successfully")
        driver.get("https://www.google.com")
        print(f"Page title: {driver.title}")
        driver.quit()
    except Exception as e:
        print(f"Error details: {str(e)}")

if __name__ == "__main__":
    test_driver()

运行脚本:python3 test_driver.py,根据报错信息针对性解决。

6. 检查防火墙与端口权限

  • VPS本地UFW防火墙:确认4444端口(若Grid在VPS)已开放:
    sudo ufw allow 4444
    sudo ufw reload
    
  • DigitalOcean控制面板防火墙:添加入站规则,允许4444端口的TCP流量(若Grid在VPS且需要外部访问);
  • 若Grid在本地,需确保本地路由器开放4444端口,且VPS的IP被允许访问该端口。

7. 确认Gunicorn运行用户权限

Gunicorn若以非root用户运行,需确保该用户能访问Chrome、ChromeDriver及相关资源:

  • 检查Chrome路径权限:ls -l /usr/bin/google-chrome
  • 确保运行Gunicorn的用户(如www-data)有执行权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 03:15:56