Firefox版Selenium Instagram Bot无法定位Follow按钮求助
Instagram Selenium Bot 元素定位与交互问题排查
需求与问题现状
我在VS Code中开发了一款Selenium Instagram Bot,核心需求:
- 从
.txt文件读取目标账号列表,逐个访问主页 - 完成关注操作,同时点赞指定数量的帖子(若账号为私密状态则仅关注)
- 轮换使用多个预先创建的Bot账号,单个Bot完成一定交互后切换至下一个
目前已实现目标账号遍历,但存在以下问题:
- 曾在单个账号上运行成功,但切换至下一个账号后Bot无任何操作,无法定位Follow按钮(修改代码后无法复现该场景)
- 点赞功能从未正常运行
- 登录及弹窗的XPATH定位功能正常,仅无法与目标账号主页进行交互
源代码
from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.firefox.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import time, random from selenium.webdriver.common.keys import Keys profilePath = (r'C:\Users\****\AppData\Roaming\Mozilla\Firefox\Profiles\75d4lwz2.3rd') options = Options() service = Service('geckodrivere.exe') firefox = webdriver.Firefox(options=options, service=service) wait = WebDriverWait(firefox, 20) file = open('scrape_archivepages.txt', 'r') data = file.read() igUsers = data.split('\n') file.close() file2 = open('botlist.txt', 'r') data2 = file2.read() bots = data2.split('\n') file2.close() def startLogIn(user_, pass_): firefox.get('https://www.instagram.com/') while True: try: cookiesAccept = firefox.find_element(By.XPATH, '/html/body/div[2]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/button[2]') time.sleep(4) cookiesAccept.click() time.sleep(4) break except: pass username = firefox.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[1]/div/label/input') password = firefox.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[2]/div/label/input') username.click() username.send_keys(user_) time.sleep(random.randint(1, 2)) password.click() password.send_keys(pass_) time.sleep(random.randint(1, 2)) log_in=firefox.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]') log_in.click() time.sleep(5) # 恢复弹窗处理逻辑 while True: try: credentials= firefox.find_element(By.XPATH, '//button[text()="Not Now"]') time.sleep(3) credentials.click() break except: pass while True: try: notifications = firefox.find_element(By.XPATH, '//button[text()="Not Now"]') time.sleep(3) notifications.click() break except: pass def interact(igUserLink, n): firefox.get(igUserLink) time.sleep(2) # 修复Follow按钮定位:使用相对定位 follow_btn = WebDriverWait(firefox, 10).until( EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, '_ab8w') and (text()='Follow' or text()='Follow Back')]")) ) # 修复私密账号判断逻辑 is_private = False try: WebDriverWait(firefox, 5).until( EC.presence_of_element_located((By.XPATH, "//h2[text()='This Account is Private']")) ) is_private = True except: pass if is_private: print(f"账号{igUserLink}为私密状态,仅执行关注") follow_btn.click() time.sleep(random.randint(2,3)) else: print(f"账号{igUserLink}为公开状态,执行关注+点赞") follow_btn.click() time.sleep(random.randint(2,3)) if n > 0: try: # 点击第一个帖子 first_post = WebDriverWait(firefox, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@class='_aagw']")) ) first_post.click() time.sleep(random.randint(1,2)) c = 0 while c < n: # 定位并点击点赞按钮 like_btn = WebDriverWait(firefox, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @aria-label='Like']")) ) like_btn.click() c +=1 time.sleep(random.randint(2,4)) # 未完成点赞则切换下一个帖子 if c < n: next_btn = WebDriverWait(firefox, 10).until( EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @aria-label='Next']")) ) next_btn.click() time.sleep(random.randint(1,2)) # 关闭帖子弹窗 close_btn = WebDriverWait(firefox, 5).until( EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @aria-label='Close']")) ) close_btn.click() except Exception as e: print(f"点赞过程出错: {str(e)}") # 出错时尝试关闭弹窗 try: close_btn = WebDriverWait(firefox, 3).until( EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @aria-label='Close']")) ) close_btn.click() except: pass def VibeFinderInteract(listOfBots, passw, userLink): # 处理空行,避免无效账号链接 userLink = [line.strip() for line in userLink if line.strip()] listOfBots = [line.strip() for line in listOfBots if line.strip()] for userbot in listOfBots: startLogIn(userbot, passw) # 单个Bot处理指定数量的账号后切换 for idx, u in enumerate(userLink): if idx >= 5: # 单个Bot处理5个账号后切换,可按需调整 break interact(u, 2) print(f"完成对{u}的操作") # 切换Bot前清除Cookie,重置会话 firefox.delete_all_cookies() time.sleep(2) VibeFinderInteract(bots, 'samepasswordforallthebots', igUsers)
核心问题修复说明
1. 脆弱的元素定位器替换
原代码使用动态ID(如mount_0_0_0I)和绝对XPATH,这类定位器会随页面结构或加载状态变化失效。改为基于语义化属性的相对定位,比如通过按钮文本、aria-label、稳定的class前缀定位元素,大幅提升稳定性。
2. 错误的私密账号判断逻辑修复
原代码直接用find_element判断私密账号,找不到元素会直接抛出异常,导致后续逻辑终止。改用try-except结合显式等待,优雅判断账号是否私密,避免程序崩溃。
3. 点赞功能逻辑重构
原代码中if n == 0的嵌套逻辑错误,导致传参n=2时点赞代码永远不会执行。重构后先判断账号是否公开,再执行点赞流程,同时添加异常捕获和弹窗关闭逻辑,避免单个帖子出错导致整个流程终止。
4. 等待机制优化
用WebDriverWait显式等待替代固定time.sleep,确保元素加载完成后再执行操作,同时保留随机延迟模拟真人行为,降低被Instagram检测的风险。
5. 账号列表与Bot状态管理
添加空行过滤逻辑,避免无效链接;单个Bot完成指定数量操作后清除Cookie,确保会话独立,避免账号状态残留影响后续操作。
内容的提问来源于stack exchange,提问作者salm p.
相关产品推荐
相关产品推荐

