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

基于无头Selenium在Ubuntu 18.04服务器向Instagram传图的方案咨询

解决Ubuntu 18.04无头Selenium上传图片到Instagram的方案

Got it, let's tackle this Instagram upload issue on Ubuntu 18.04 with headless Selenium—since AutoIt's only for Windows and doesn't play nice with headless mode, here's the most reliable workaround I've used for this exact scenario:

方案1:利用Chrome DevTools Protocol (CDP) 直接模拟文件上传

Instagram's upload flow doesn't expose a visible file input in the DOM, but CDP lets us bypass that entirely by communicating directly with the browser. This works perfectly in headless mode and on Linux systems like Ubuntu.

Here's how to implement it step by step:

  1. 初始化带CDP支持的无头Chrome驱动
    确保ChromeDriver版本和你安装的Chrome浏览器主版本匹配:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    chrome_options.add_argument("--headless=new")  # 新版无头模式更稳定
    chrome_options.add_argument("--no-sandbox")
    chrome_options.add_argument("--disable-dev-shm-usage")
    chrome_options.add_argument("--disable-gpu")  # 旧版无头模式兼容项,可选
    
    driver = webdriver.Chrome(options=chrome_options)
    
  2. 登录Instagram并进入上传界面
    用你已有的登录代码完成账号登录,然后点击"创建帖子"按钮进入上传流程。

  3. 通过CDP注入图片路径
    Page.setFileInputFiles这个CDP命令可以直接指定要上传的文件,完全不需要操作DOM元素:

    # 获取当前页面的主框架ID,确保命令作用在正确上下文
    frame_tree = driver.execute_cdp_cmd("Page.getFrameTree", {})
    main_frame_id = frame_tree["frameTree"]["frame"]["id"]
    
    # 替换成你的图片绝对路径
    image_path = "/home/your-user/path/to/your/image.jpg"
    
    # 执行文件上传命令
    driver.execute_cdp_cmd(
        "Page.setFileInputFiles",
        {
            "frameId": main_frame_id,
            "files": [image_path]
        }
    )
    
  4. 完成后续帖子设置
    执行完CDP命令后,Instagram会自动加载你的图片。接下来你就可以用Selenium正常添加文案、标签,最后点击"分享"按钮即可。

关键注意事项

  • Chrome/ChromeDriver版本匹配: 一定要保证ChromeDriver版本和安装的Chrome主版本一致,版本不匹配会导致CDP命令失效。
  • 使用绝对路径: 图片路径务必用完整绝对路径,避免无头模式下工作目录不确定导致的"文件找不到"错误。
  • 权限设置: 运行脚本的用户需要有图片文件的读取权限,以及Chrome临时上传目录的写入权限。

备选方案:使用undetected-chromedriver(应对反爬检测)

如果常规Selenium/CDP被Instagram的反爬机制拦截,可以换成undetected-chromedriver——它会修改ChromeDriver规避检测,同时依然支持CDP命令。初始化代码只需稍作修改:

import undetected_chromedriver as uc

chrome_options = uc.ChromeOptions()
chrome_options.add_argument("--headless=new")
chrome_options.add_argument("--no-sandbox")

driver = uc.Chrome(options=chrome_options)

之后的CDP上传步骤和方案1完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:57:46