Selenium操作Instagram弹窗滚动失败及元素定位报错问题
Instagram爬虫自动化弹窗定位失败问题
我用Python+Selenium实现Instagram自动化操作:登录账号→进入指定账号主页→打开关注列表弹窗→滚动弹窗并关注可见用户。目前程序能完成登录、进入目标账号、点击关注列表按钮,但始终无法定位弹窗元素,报NoSuchElementException,更换多个XPATH也无效,导致无法执行滚动和关注操作。
原代码
import time from selenium.common.exceptions import ElementClickInterceptedException import selenium as selenium from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium import webdriver SIMILAR_ACCOUNT = "honeymoon" USERNAME = "username" PASSWORD = "password" class InstaFollower: def __init__(self): chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("detach", True) self.driver = webdriver.Chrome(options=chrome_options) self.driver.get("https://www.instagram.com") def login(self): self.driver.get("https://www.instagram.com") login_form = WebDriverWait(self.driver, 10).until( EC.presence_of_element_located((By.XPATH, '//*[@id="loginForm"]'))) username = login_form.find_element(By.NAME, 'username') password = login_form.find_element(By.NAME, 'password') login_button = login_form.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button') username.send_keys(USERNAME) password.send_keys(PASSWORD) login_button.click() WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, '//*[@aria-label="Instagram"]'))) def find_followers(self): time.sleep(5) self.driver.get(f"https://www.instagram.com/{SIMILAR_ACCOUNT}/followers") time.sleep(5.2) modal_xpath = ('/html/body/div[6]/div[1]/div/div[2]/div/div/div/div/div[2]/div/div') modal = self.driver.find_element(by=By.XPATH, value=modal_xpath) for i in range(10): self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", modal) WebDriverWait(self.driver, 10).until(EC.presence_of_element_located((By.XPATH, modal_xpath))) def follow(self): all_buttons = self.driver.find_elements(By.XPATH, value='/html/body/div[6]/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[4]/div[1]/div/div[1]/div/div/div/div[3]/div/button/div/div') for button in all_buttons: try: button.click() time.sleep(1.1) except ElementClickInterceptedException: cancel_button = self.driver.find_element(by=By.XPATH, value="//button[contains(text(), 'Cancel')]") cancel_button.click() bot = InstaFollower() bot.login() bot.find_followers() bot.follow()
报错信息
Traceback (most recent call last): File "C:\Users\38161\PycharmProjects\ InstagramFollowerBot\main.py", line 78, in <module> bot.find_followers() File "C:\Users\38161\PycharmProjects\ InstagramFollowerBot\main.py", line 52, in find_followers modal = self.driver.find_element(by=By.XPATH, value=modal_xpath) File "C:\Users\38161\PycharmProjects\ InstagramFollowerBot\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 742, in find_element return self.execute(Command.FIND_ELEMENT, {"using": by, "value": value})["value"] File "C:\Users\38161\PycharmProjects\ InstagramFollowerBot\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 348, in execute self.error_handler.check_response(response) File "C:\Users\38161\PycharmProjects\ InstagramFollowerBot\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 229, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[6]/div[1]/div/div[2]/div/div/div/div/div[2]/div/div"} (Session info: chrome=120.0.6099.111); For documentation on this error, please visit: https://www.selenium.dev/documentation/webdriver/troubleshooting/errors#no-such-element-exception Stacktrace: GetHandleVerifier [0x00007FF657C32142+3514994] (No symbol) [0x00007FF657850CE2] (No symbol) [0x00007FF6576F76AA] (No symbol) [0x00007FF657741860] (No symbol) [0x00007FF65774197C] (No symbol) [0x00007FF657784EE7] (No symbol) [0x00007FF65776602F] (No symbol) [0x00007FF6577828F6] (No symbol) [0x00007FF657765D93] (No symbol) [0x00007FF657734BDC] (No symbol) [0x00007FF657735C64] GetHandleVerifier [0x00007FF657C5E16B+3695259] GetHandleVerifier [0x00007FF657CB6737+4057191] GetHandleVerifier [0x00007FF657CAE4E3+4023827] GetHandleVerifier [0x00007FF6579804F9+689705] (No symbol) [0x00007FF65785C048] (No symbol) [0x00007FF657858044] (No symbol) [0x00007FF6578581C9] (No symbol) [0x00007FF6578488C4] BaseThreadInitThunk [0x00007FF896867344+20] RtlUserThreadStart [0x00007FF896E626B1+33]
问题原因及修复方案
1. 核心问题:绝对XPATH不稳定
你使用的绝对XPATH(/html/body/div[6]/...)完全依赖页面DOM的层级结构,而Instagram的弹窗div索引(比如div[6])会因页面动态元素(如通知弹窗、登录提示)变化而改变,完全不可靠。
2. 修复后的代码
import time from selenium.common.exceptions import ElementClickInterceptedException from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium import webdriver SIMILAR_ACCOUNT = "honeymoon" USERNAME = "username" PASSWORD = "password" class InstaFollower: def __init__(self): chrome_options = webdriver.ChromeOptions() chrome_options.add_experimental_option("detach", True) self.driver = webdriver.Chrome(options=chrome_options) self.driver.get("https://www.instagram.com") self.wait = WebDriverWait(self.driver, 15) # 统一设置显式等待时长 def login(self): # 等待登录表单加载 login_form = self.wait.until(EC.presence_of_element_located((By.ID, 'loginForm'))) username = login_form.find_element(By.NAME, 'username') password = login_form.find_element(By.NAME, 'password') login_button = login_form.find_element(By.XPATH, './/button[@type="submit"]') # 相对定位提交按钮 username.send_keys(USERNAME) password.send_keys(PASSWORD) login_button.click() # 处理"保存登录信息"弹窗 try: save_login_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Not Now"]'))) save_login_btn.click() except: pass # 处理"开启通知"弹窗 try: notif_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Not Now"]'))) notif_btn.click() except: pass def find_followers(self): # 进入目标账号主页 self.driver.get(f"https://www.instagram.com/{SIMILAR_ACCOUNT}/") # 等待并点击关注列表按钮 followers_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "/followers/")]'))) followers_btn.click() # 等待关注列表弹窗加载,用固定类名定位(更稳定) modal = self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, '_aano'))) # 滚动弹窗加载更多用户 for _ in range(10): self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", modal) time.sleep(1) # 给新内容加载留缓冲时间 def follow(self): # 定位所有未关注的"Follow"按钮 follow_buttons = self.wait.until(EC.presence_of_all_elements_located( (By.XPATH, '//div[@class="_aano"]//button[text()="Follow"]') )) for button in follow_buttons: try: button.click() time.sleep(1) except ElementClickInterceptedException: # 处理误点已关注用户后的取消弹窗 cancel_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Cancel"]'))) cancel_btn.click() time.sleep(0.5) bot = InstaFollower() bot.login() bot.find_followers() bot.follow()
3. 关键修复点说明
- 替换绝对XPATH:用
By.CLASS_NAME定位弹窗(_aano是Instagram关注列表弹窗的固定类名),按钮用文本内容+相对路径定位,避免DOM结构变化导致定位失效。 - 移除固定sleep:用
WebDriverWait替代time.sleep,确保元素加载完成后再操作,同时处理登录后的两个干扰弹窗。 - 滚动逻辑优化:滚动后添加短时间sleep,让新的关注用户完全加载,避免重复滚动空内容。
内容的提问来源于stack exchange,提问作者luna28blue
相关产品推荐
相关产品推荐

