使用Selenium WebDriver登录Instagram时的点击及连接异常问题
Instagram Selenium登录问题排查与解决
问题现象
使用Selenium WebDriver登录Instagram时,WebDriver无法点击「Log in」按钮;手动点击该按钮则返回错误提示:
Failed to connect to Instagram. Make sure you are connected to the Internet and try again.
但直接打开Chrome手动登录完全正常,此前执行登录存Cookie的操作无此问题。
已完成排查
- 检查IP限制:尝试过VPN
- 排查网络限制:更换过网络
- 重新安装chromedriver
相关代码
from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.chrome.options import Options option = webdriver.ChromeOptions() option.add_experimental_option("excludeSwitches", ["enable-automation"]) option.add_experimental_option('useAutomationExtension', False) option.add_argument("option.add_argument('--disable-blink-features=AutomationControlled')") driver = webdriver.Chrome(chrome_options=option, executable_path=r'C:\Users\Юзернейм\Desktop\chromedriver.exe') driver.get(f'https://www.instagram.com/') user_data_name = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']"))) user_data_password = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='password']"))) user_data_name.clear() user_data_password.clear() user_data_name.send_keys("log") user_data_password.send_keys("pass") log_in = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']"))).click()
解决方案
1. 修复ChromeOptions配置错误
代码里add_argument行存在语法错误,把整行代码当成字符串传入了,正确写法应为:
option.add_argument('--disable-blink-features=AutomationControlled')
错误配置会导致防自动化标识未被禁用,Instagram检测到自动化工具访问后限制了操作。
2. 补充防检测配置
添加以下配置让浏览器更接近真实手动环境:
option.add_argument('--no-sandbox') option.add_argument('--disable-dev-shm-usage') option.add_argument('--disable-gpu') # 替换成你当前Chrome的真实用户代理,可通过浏览器访问about:version查看 option.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36')
3. 改用回车提交登录
若按钮点击被拦截,可在输入密码后直接按回车提交:
user_data_password.send_keys("pass", Keys.ENTER)
4. 复用本地Chrome用户数据
调用本地Chrome的用户数据目录,直接复用已登录会话,无需重复输入账号密码:
# 替换为你的Chrome用户数据路径,Windows默认路径示例: option.add_argument(r'user-data-dir=C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data') # 指定配置文件,避免影响默认浏览器会话 option.add_argument('--profile-directory=Default')
5. 增加页面加载等待
在driver.get后添加显式等待,确保页面完全加载:
driver.get('https://www.instagram.com/') WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
内容的提问来源于stack exchange,提问作者Watyeraty
相关产品推荐
相关产品推荐

