如何修复Instagram机器人中的AttributeError: 'NoneType'对象无click属性
Instagram Selenium机器人修复:AttributeError: 'NoneType' object has no attribute 'click'
运行基于Selenium开发的Instagram自动化机器人代码时,触发以下错误:
AttributeError: 'NoneType' object has no attribute 'click'
完整错误日志
D:\Users\singh\PycharmProjects\IG-Bot-main\fuf.py:21: DeprecationWarning: executable_path has been deprecated, please pass in a Service object browser = webdriver.Chrome(executable_path=ChromeDriverManager().install(), options=options) Traceback (most recent call last): File "D:\Users\singh\PycharmProjects\IG-Bot-main\fuf.py", line 77, in <module> main() File "D:\Users\singh\PycharmProjects\IG-Bot-main\fuf.py", line 33, in main login_button.click() AttributeError: 'NoneType' object has no attribute 'click' Process finished with exit code 1
问题根源
错误出在login_button.click(),说明browser.find_element_by_xpath("//button[@type='submit']")未找到目标元素,返回了None。主要原因包括:
- 固定
time.sleep(5)无法保证页面元素完全加载,网络延迟时元素还未渲染完成 - Instagram页面结构可能更新,原XPath定位规则失效
- Selenium版本兼容性问题(
executable_path参数已被废弃)
修复后的完整代码
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager import random 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 def sleep_for_period_of_time(): limit = random.randint(7,10) time.sleep(limit) user = input("Enter your username: ") pwd = input("Enter your password: ") def main(): options = webdriver.ChromeOptions() options.add_argument("--lang=en") # 修复Selenium 4.x废弃的executable_path参数 from selenium.webdriver.chrome.service import Service service = Service(ChromeDriverManager().install()) browser = webdriver.Chrome(service=service, options=options) browser.get("https://www.instagram.com") # 用显式等待替代固定sleep,确保元素加载完成 wait = WebDriverWait(browser, 10) # 等待用户名/密码输入框加载 username_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='username']"))) password_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[name='password']"))) username_input.send_keys(user) password_input.send_keys(pwd) sleep_for_period_of_time() # 等待登录按钮可点击,使用更稳定的定位规则 login_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@type='submit']"))) login_button.click() sleep_for_period_of_time() # 处理"Not Now"弹窗,添加异常捕获避免找不到元素中断程序 try: not_now = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Not Now']"))) not_now.click() sleep_for_period_of_time() except: pass page_ig = input("Enter page username: ") browser.get(f"https://www.instagram.com/{page_ig}") sleep_for_period_of_time() # 等待粉丝链接加载,改用href属性定位更稳定 followers_link = wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href, '/followers/')]"))) followers_link.click() sleep_for_period_of_time() num_follow = int(input("How many person you want to follow: ")) # 重构循环逻辑,避免索引越界问题 follow_count = 0 while follow_count < num_follow: try: # 等待可关注按钮加载 follow_buttons = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//button[text()="Follow"]'))) for button in follow_buttons: if button.text == "Follow" and follow_count < num_follow: button.click() follow_count += 1 print(f"Followed! Current count: {follow_count}") sleep_for_period_of_time() # 滚动到当前按钮,触发更多粉丝加载 browser.execute_script("arguments[0].scrollIntoView(true);", button) # 无更多可关注用户时退出循环 if not follow_buttons: print("No more followable users available.") break except Exception as e: print(f"Error: {e}") # 遇到错误时滚动页面尝试加载更多内容 if follow_buttons: browser.execute_script("arguments[0].scrollIntoView(true);", follow_buttons[-1]) else: browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") sleep_for_period_of_time() answer = input("The program finished! Enter 'e' to exit.. ") if answer.lower().startswith("e"): browser.quit() if __name__ == "__main__": main()
核心修复点
- 显式等待替代固定sleep:使用
WebDriverWait等待元素存在/可点击,彻底解决元素未加载导致的NoneType错误 - 修复Selenium版本兼容问题:改用
Service对象传递驱动路径,消除executable_path废弃警告 - 优化元素定位:调整粉丝链接、弹窗按钮的定位逻辑,适配Instagram页面结构变化
- 循环逻辑重构:避免原代码中索引越界问题,确保达到目标关注数后正常退出
- 异常处理增强:对可能出现的元素未找到情况添加捕获,提升程序稳定性
内容的提问来源于stack exchange,提问作者Abhay Singh
相关产品推荐
相关产品推荐

