Instagram关注机器人无法点击关注按钮及滚动列表问题求助
解决方案
1. 更新元素定位器(适配Instagram最新页面结构)
原代码中使用的isgrP类名已被Instagram废弃,当前粉丝列表弹窗的滚动容器类名为_aano,修改等待逻辑:
followers_list = WebDriverWait(self.driver, 10).until( EC.visibility_of_element_located((By.XPATH, "//div[@role='dialog']//div[@class='_aano']")) )
2. 替换为可靠的JavaScript滚动
原Space键滚动方式不稳定,改用JS控制滚动容器的滚动条:
# 替换原滚动循环代码 last_height = self.driver.execute_script("return arguments[0].scrollHeight", followers_list) while True: # 滚动到底部 self.driver.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_list) time.sleep(2) # 等待加载新内容 new_height = self.driver.execute_script("return arguments[0].scrollHeight", followers_list) # 高度不变说明已加载完所有内容 if new_height == last_height: break last_height = new_height
3. 修复关注按钮定位逻辑
直接通过文本定位容易失效,改用按钮的特征类名定位,并跳过已关注的按钮:
def follow(self): try: # 定位所有未关注的按钮 buttons = self.driver.find_elements(By.XPATH, "//button[contains(@class, '_acan') and contains(@class, '_acap') and contains(@class, '_acas')]") for button in buttons: # 只处理显示"Follow"的按钮 if button.text.strip() == "Follow": self.driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", button) time.sleep(1) button.click() time.sleep(3) except Exception as e: print(e)
4. 升级ChromeDriver初始化方式
executable_path已被Selenium弃用,改用Service类初始化:
def __init__(self, path): service = Service(path) self.driver = webdriver.Chrome(service=service)
5. 处理登录后的弹窗
登录后会出现"保存登录信息"和"通知权限"弹窗,需添加处理逻辑避免阻塞:
def login(self): self.driver.get(url=INSTA_URL) time.sleep(3) # 输入账号密码 username = self.driver.find_element(By.NAME, value="username") username.send_keys(INSTA_USERNAME) password = self.driver.find_element(By.NAME, value="password") password.send_keys(INSTA_PASSWORD) password.send_keys(Keys.ENTER) time.sleep(5) # 关闭"保存登录信息"弹窗 try: not_now = self.driver.find_element(By.XPATH, "//div[text()='Not Now']") not_now.click() time.sleep(3) except: pass # 关闭"通知权限"弹窗 try: not_now_notif = self.driver.find_element(By.XPATH, "//button[text()='Not Now']") not_now_notif.click() time.sleep(3) except: pass
内容的提问来源于stack exchange,提问作者Ziya Safar
相关产品推荐
相关产品推荐

