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

Python+Selenium实现Instagram自动评论遇元素过期异常求助

问题

尝试用Python和Selenium自动化Instagram帖子评论,试过CLASS_NAME、TAG_NAME、XPATH、CSS_SELECTOR等多种元素定位方式,也用了显式等待确保元素加载,但始终定位不到评论输入框,执行send_keys时触发StaleElementReferenceException错误。以下是代码和报错信息,求指导如何正确定位评论输入框、输入内容并提交评论。

原始代码

from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json
import os
import pickle
from selenium import __version__


data = {
'username' : 'wendyturner329ysu',
'password' : 'MpEgPAhd',
'url_publication' : 'https://www.instagram.com/p/ClZj_e4vZCF/',
'comment' : 'This is an automated comment!',
'time' : 3
}
def Comments():
    driver = webdriver.Chrome()
    driver.get("https://www.instagram.com")
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        if cookie['domain'] == ".instagram.com":
            try:
                driver.add_cookie(cookie)
            except Exception as e:
                print(e)
    driver.get("https://www.instagram.com/p/ClZj_e4vZCF/")
    time.sleep(4)
    driver.find_element(By.XPATH, '//textarea[@aria-label="Add a comment..."]').send_keys(data['comment'])

    time.sleep(5)
Comments()

对应报错信息

C:\Users\54225\AppData\Local\Programs\Python\Python310\python.exe C:/Users/54225/Documentos/Proyecto/Comentarios_Instagram_Selenium.py
Traceback (most recent call last):
  File "C:\Users\54225\Documentos\Proyecto\Comentarios_Instagram_Selenium.py", line 39, in <module>
    Comentarios()
  File "C:\Users\54225\Documentos\Proyecto\Comentarios_Instagram_Selenium.py", line 36, in Comentarios
    driver.find_element(By.XPATH, '//textarea[@aria-label="Agrega un comentario..."]').send_keys(datos['comentario'])
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 233, in send_keys
    self._execute(
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 410, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=109.0.5414.75)
Stacktrace:
Backtrace:
    (No symbol) [0x00F36643]
    (No symbol) [0x00ECBE21]
    (No symbol) [0x00DCDA9D]
    (No symbol) [0x00DD09E4]
    (No symbol) [0x00DD08AD]
    (No symbol) [0x00DD0B30]
    (No symbol) [0x00DFC474]
    (No symbol) [0x00DFB7AB]
    (No symbol) [0x00E1FD7C]
    (No symbol) [0x00DF641F]
    (No symbol) [0x00E200D4]
    (No symbol) [0x00E36B09]
    (No symbol) [0x00E1FB76]
    (No symbol) [0x00DF49C1]
    (No symbol) [0x00DF5E5D]
    GetHandleVerifier [0x011AA142+2497106]
    GetHandleVerifier [0x011D85D3+2686691]
    GetHandleVerifier [0x011DBB9C+2700460]
    GetHandleVerifier [0x00FE3B10+635936]
    (No symbol) [0x00ED4A1F]
    (No symbol) [0x00EDA418]
    (No symbol) [0x00EDA505]
    (No symbol) [0x00EE508B]
    BaseThreadInitThunk [0x7612FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x770A7BBE+286]
    RtlGetAppContainerNamedObjectPath [0x770A7B8E+238]


Process finished with exit code 1

使用显式等待的代码

datos = {
'usuario' : 'wendyturner329ysu',
'contraseña' : 'MpEgPAhd',
'url_publicacion' : 'https://www.instagram.com/p/ClZj_e4vZCF/',
'comentario' : 'Este es un comentario automatizado!',
'tiempo' : 3
}
def Comentarios():
    """Lo que esta comentado es para usar un proxy especifico"""
    #proxy = "136.228.220.49:8082"
    #options = webdriver.ChromeOptions()
    #options.add_argument('--proxy-server=%s' % proxy)
    #driver = webdriver.Chrome(chrome_options=options)
    driver = webdriver.Chrome()
    driver.get("https://www.instagram.com")
    cookies = pickle.load(open("cookies.pkl","rb"))
    for cookie in cookies:
        if cookie['domain'] == ".instagram.com":
            try:
                driver.add_cookie(cookie)
            except Exception as e:
                print(e)
    driver.get("https://www.instagram.com/p/ClZj_e4vZCF/")
    time.sleep(4)
    wait = WebDriverWait(driver, 10)
    comment_box = wait.until(EC.presence_of_element_located((By.XPATH, '//textarea[@aria-label="Agrega un comentario..."]')))
    comment_box.send_keys(datos['comentario'])

对应报错信息

Traceback (most recent call last):
  File "C:\Users\54225\Documentos\Proyecto\Comentarios_Instagram_Selenium.py", line 42, in <module>
    Comentarios()
  File "C:\Users\54225\Documentos\Proyecto\Comentarios_Instagram_Selenium.py", line 38, in Comentarios
    comment_box.send_keys(datos['comentario'])
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 233, in send_keys
    self._execute(
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webelement.py", line 410, in _execute
    return self._parent.execute(command, params)
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 444, in execute
    self.error_handler.check_response(response)
  File "C:\Users\54225\AppData\Local\Programs\Python\Python310\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 249, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
  (Session info: chrome=109.0.5414.75)
Stacktrace:
Backtrace:
    (No symbol) [0x00F36643]
    (No symbol) [0x00ECBE21]
    (No symbol) [0x00DCDA9D]
    (No symbol) [0x00DD09E4]
    (No symbol) [0x00DD08AD]
    (No symbol) [0x00DD0B30]
    (No symbol) [0x00DFC474]
    (No symbol) [0x00DFB7AB]
    (No symbol) [0x00E1FD7C]
    (No symbol) [0x00DF641F]
    (No symbol) [0x00E200D4]
    (No symbol) [0x00E36B09]
    (No symbol) [0x00E1FB76]
    (No symbol) [0x00DF49C1]
    (No symbol) [0x00DF5E5D]
    GetHandleVerifier [0x011AA142+2497106]
    GetHandleVerifier [0x011D85D3+2686691]
    GetHandleVerifier [0x011DBB9C+2700460]
    GetHandleVerifier [0x00FE3B10+635936]
    (No symbol) [0x00ED4A1F]
    (No symbol) [0x00EDA418]
    (No symbol) [0x00EDA505]
    (No symbol) [0x00EE508B]
    BaseThreadInitThunk [0x7612FEF9+25]
    RtlGetAppContainerNamedObjectPath [0x770A7BBE+286]
    RtlGetAppContainerNamedObjectPath [0x770A7B8E+238]

解决方案

错误原因

StaleElementReferenceException本质是:定位到的元素在DOM中被重新渲染(比如页面动态加载、组件刷新),导致之前获取的元素引用失效。Instagram的评论区是动态组件,页面跳转后可能仍在异步渲染,即便用了presence_of_element_located,元素也可能很快被替换。

修正步骤与代码

1. 优化定位策略

Instagram评论输入框初始是textarea,点击后会切换为input,改用[role="textbox"]结合包含"comentario"的aria-label定位,稳定性更高。

2. 等待元素可交互

放弃仅等待元素存在,改用element_to_be_clickable确保元素能接收用户输入。

3. 修正登录逻辑

添加页面刷新确保cookies生效,避免未登录状态无法评论。

完整修正代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import StaleElementReferenceException
import pickle

datos = {
    'usuario': 'wendyturner329ysu',
    'contraseña': 'MpEgPAhd',
    'url_publicacion': 'https://www.instagram.com/p/ClZj_e4vZCF/',
    'comentario': 'Este es un comentario automatizado!',
    'tiempo': 3
}

def Comentarios():
    driver = webdriver.Chrome()
    driver.get("https://www.instagram.com")
    
    # 加载cookies并刷新页面确保生效
    cookies = pickle.load(open("cookies.pkl", "rb"))
    for cookie in cookies:
        if cookie['domain'] == ".instagram.com":
            try:
                driver.add_cookie(cookie)
            except Exception as e:
                print(e)
    driver.refresh()
    
    # 跳转目标帖子页面
    driver.get(datos['url_publicacion'])
    
    wait = WebDriverWait(driver, 15)
    success = False
    
    # 循环处理元素失效问题,直到成功输入
    while not success:
        try:
            # 定位评论输入框
            comment_box = wait.until(EC.element_to_be_clickable(
                (By.XPATH, '//*[@role="textbox" and contains(@aria-label,"comentario")]')
            ))
            comment_box.send_keys(datos['comentario'])
            success = True
        except StaleElementReferenceException:
            continue
    
    # 定位并点击发布按钮
    submit_btn = wait.until(EC.element_to_be_clickable(
        (By.XPATH, '//div[@role="button" and contains(text(),"Publicar")]')
    ))
    submit_btn.click()
    
    driver.quit()

Comentarios()

额外注意事项

  • Instagram有严格的反爬机制,频繁自动化评论可能导致账号受限,建议添加随机延迟(比如time.sleep(random.randint(3,7))),避免固定操作间隔。
  • 定期更新cookies,失效的cookies会导致未登录状态,无法执行评论操作。
  • 如果遇到验证码或人机验证,需手动处理,或集成验证码识别工具(但不推荐,违反Instagram规则)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 23:55:32