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

Python Selenium实现Instagram图片上传故障排查求助

Instagram图片上传Selenium脚本修复方案

问题诊断

你的脚本在处理通知弹窗后停止运行,核心原因包括:

  • 缺少**点击创建按钮(首页的+图标)**的关键步骤,直接尝试定位文件上传输入框
  • 重复跳转首页导致页面状态混乱
  • 部分元素定位的XPATH错误(如占位符//element_on_second_screen、错误的按钮文本)
  • 依赖time.sleep而非显式等待,导致元素未加载完成就执行操作

修复后的完整代码

import os
import random
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service

def upload_images(username, password, image_folder):
    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    # 可选:添加无头模式或其他配置
    # options.add_argument('--headless=new')

    # 指定ChromeDriver路径
    s = Service('chromedriver.exe')
    driver = webdriver.Chrome(service=s, options=options)
    wait = WebDriverWait(driver, 15)

    try:
        # 登录流程
        driver.get('https://www.instagram.com/accounts/login/')
        # 等待用户名输入框加载
        username_input = wait.until(EC.visibility_of_element_located((By.NAME, 'username')))
        password_input = wait.until(EC.visibility_of_element_located((By.NAME, 'password')))
        
        username_input.send_keys(username)
        password_input.send_keys(password)
        password_input.send_keys(Keys.ENTER)

        # 处理"保存登录信息"弹窗
        try:
            wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Not Now']"))).click()
        except:
            pass

        # 处理通知权限弹窗
        try:
            wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Not Now']"))).click()
        except:
            pass

        # 获取文件夹内的图片文件
        image_files = [file for file in os.listdir(image_folder) if file.endswith(('.jpg', '.jpeg', '.png'))]
        if not image_files:
            print("文件夹内无图片文件")
            return

        for image_file in image_files:
            image_path = os.path.abspath(os.path.join(image_folder, image_file))
            print(f"准备上传: {image_path}")

            # 回到首页并点击创建按钮(+图标)
            driver.get('https://www.instagram.com/')
            create_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@aria-label, 'Create')]")))
            create_btn.click()

            # 定位文件上传输入框并发送图片路径
            upload_input = wait.until(EC.presence_of_element_located((By.XPATH, "//input[@type='file']")))
            upload_input.send_keys(image_path)
            print("图片已提交上传")

            # 点击第一个Next按钮(图片编辑页面)
            first_next = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Next']")))
            first_next.click()

            # 点击第二个Next按钮(滤镜/设置页面)
            second_next = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Next']")))
            second_next.click()

            # 可选:添加文案(如果需要)
            # caption_input = wait.until(EC.visibility_of_element_located((By.XPATH, "//textarea[@aria-label='Write a caption…']")))
            # caption_input.send_keys("自动上传的图片")

            # 点击Share按钮完成上传
            share_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Share']")))
            share_btn.click()

            # 等待上传完成,避免频繁操作
            wait.until(EC.invisibility_of_element_located((By.XPATH, "//button[text()='Share']")))
            print(f"{image_file} 上传成功")

            # 随机等待,模拟人工操作
            time.sleep(random.randint(8, 15))

    except Exception as e:
        print(f"执行出错: {str(e)}")
    finally:
        driver.quit()

# 调用示例
# upload_images("你的用户名", "你的密码", "图片文件夹路径")

关键修复点说明

  • 添加创建按钮点击步骤:通过//div[contains(@aria-label, 'Create')]定位首页的+图标,这是上传流程的起始入口
  • 统一使用显式等待:用WebDriverWait替代time.sleep,确保元素加载完成后再操作,避免超时或无效点击
  • 修正元素定位:移除错误的占位符XPATH,统一使用Instagram实际的按钮文本和元素属性
  • 增加错误处理:添加全局异常捕获,确保脚本出错时能关闭浏览器
  • 模拟人工操作间隔:上传完成后添加随机等待,降低被反爬检测的风险

注意事项

  • 确保ChromeDriver版本与你的Chrome浏览器版本完全匹配,否则会出现兼容性问题
  • 如果你的Instagram界面是中文,需要将按钮文本从'Not Now'改为'稍后再说','Next'改为'下一步','Share'改为'分享'
  • 避免短时间内批量上传大量图片,Instagram会限制频繁操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:53:12