使用Python Selenium开发Instagram Bot时遇TypeError错误求助
问题解决:Instagram Bot登录时的TypeError及元素定位问题
错误原因分析
你遇到的TypeError: 'str' object is not callable是因为调用方式错误:By.XPATH是一个字符串常量(值为"xpath"),不是可调用的函数,不能写成By.XPATH('xxx'),正确写法是把它作为find_element的第一个参数,定位表达式作为第二个参数。
另外你用的XPATH里的mount_0_0_9k是Instagram页面的动态ID,每次页面加载都会变化,就算修复调用错误,后续也会找不到元素,得换更稳定的定位方式。
修复后的代码
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service import time CHROME_DRIVER_PATH = "你的ChromeDriver路径" service = Service(CHROME_DRIVER_PATH) options = webdriver.ChromeOptions() options.add_experimental_option("detach", True) class InstaBot: def __init__(self): self.driver = webdriver.Chrome(service=service, options=options) def login(self): self.driver.get("https://www.instagram.com/accounts/login/") # 等待页面加载,避免元素未渲染完成 time.sleep(2) # 用按钮文本定位,适配多语言 try: accept_button = self.driver.find_element(By.XPATH, '//button[contains(text(), "接受")]') accept_button.click() except: accept_button = self.driver.find_element(By.XPATH, '//button[contains(text(), "Accept")]') accept_button.click() bot = InstaBot() bot.login()
额外优化建议
- 必须导入
from selenium.webdriver.common.by import By,否则By.XPATH会报错 - 固定
time.sleep不够灵活,推荐用显式等待替代,能更精准地等待元素可点击:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 替换time.sleep(2) accept_button = WebDriverWait(self.driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "接受")]')) ) accept_button.click() - Instagram有反爬机制,测试时放慢操作节奏,避免触发人机验证
内容的提问来源于stack exchange,提问作者mrt
相关产品推荐
相关产品推荐

