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

Instagram点赞脚本本地触发Selenium TimeoutException问题求助

Instagram Selenium脚本TimeoutException问题解决

核心问题分析

错误卡在登录步骤的Cookie授权按钮等待环节,本质原因是:

  • 你用的是绝对XPATH(/html/body/div[4]/div/div/button[2]),这种路径完全依赖页面DOM的固定层级,但Instagram的弹窗元素索引会因地区/语言设置、浏览器缓存、加载顺序不同而变化,你和朋友的环境差异导致索引不匹配
  • 等待时间仅1秒,网络慢时元素还没加载完成就触发超时
  • 代码里同时指定了本地chromedriver.exe和WebDriverManager下载的驱动,存在版本冲突

具体修复方案

1. 替换不稳定的绝对XPATH

放弃绝对路径,改用Instagram官方的测试ID或按钮文本定位,兼容性更强:

# 推荐用data-testid属性定位(最稳定)
WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='cookie-accept-all']"))).click()

# 备用:中文环境按按钮文本定位
WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '允许全部')]"))).click()

2. 延长等待时间+兼容弹窗不存在的情况

把delay从1秒改成10秒,同时加异常捕获,避免已授权Cookie时脚本中断:

delay = 10  # 延长等待时间
def login():
    driver.get('https://www.instagram.com/accounts/login/')
    os.system('cls')
    # 处理Cookie弹窗,没找到就跳过
    try:
        cookie_btn = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='cookie-accept-all']")))
        cookie_btn.click()
    except:
        print("Cookie弹窗未出现,跳过")
    sleep(1)
    # 后续登录代码不变...

3. 修复ChromeDriver初始化冲突

代码里同时指定本地驱动和WebDriverManager下载的驱动会冲突,删掉本地路径参数:

# 替换原驱动初始化代码
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s, options=chrome_options)  # 移除r'chromedriver.exe'

4. 优化浏览器选项防检测

添加参数模拟真实用户环境,降低被Instagram识别为自动化工具的概率:

chrome_options = Options()
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--start-maximized")  # 最大化窗口
chrome_options.add_argument("--disable-blink-features=AutomationControlled")  # 禁用自动化标记
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)

完整修改后的代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as EC
import os
from time import sleep

chrome_options = Options()
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)

# 修复驱动冲突
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s, options=chrome_options)

delay = 10
def login():
    driver.get('https://www.instagram.com/accounts/login/')
    os.system('cls')
    # 兼容不同场景的Cookie弹窗
    try:
        cookie_btn = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='cookie-accept-all']")))
        cookie_btn.click()
    except:
        try:
            cookie_btn = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), '允许全部')]")))
            cookie_btn.click()
        except:
            print("Cookie授权按钮未找到,跳过")
    sleep(1)
    # 登录逻辑加等待,避免元素未加载
    try:
        username = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.NAME, 'username')))
        user = input("输入你的用户名: ")
        username.send_keys(user)
        
        password = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.NAME, 'password')))
        passwd = input("输入你的密码: ")
        password.send_keys(passwd)
        password.send_keys(Keys.RETURN)
        sleep(5)
        print('登录成功')
    except Exception as e:
        print(f"登录出错: {e}")
    return driver

login()

def storieslike():
    with open("followers.txt", "r+", encoding="utf8") as f:
        for row in f:
            row = row.strip()  # 去掉换行符,避免URL错误
            if not row:
                continue
            driver.get(f'https://www.instagram.com/stories/{row}/')
            sleep(4)
            try:
                WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div/div[1]/div/div[1]/div/div/div[1]/div[1]/section/main/div/div/article/div[1]')))
                print(f"{row} 是私密账号,跳过...")
            except:
                try:
                    like_btn1 = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[1]/div/div[1]/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[1]/div/div/div/div[3]/button')))
                    like_btn1.click()
                    sleep(1)
                    like_btn2 = WebDriverWait(driver, delay).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div/div[1]/div/div[1]/div/div/div[1]/div[1]/section/div[1]/div/section/div/div[3]/div/div/div[2]/span/button')))
                    like_btn2.click()
                    print(f"已点赞 {row} 的故事")
                except Exception as e:
                    print(f"点赞 {row} 的故事失败: {e}")

storieslike()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:57:39