You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python类编写的Selenium程序无法启动、web驱动打不开问题咨询

问题原因

  • 缺失必要模块导入语句:未导入selenium.webdriver、time模块,运行直接触发未定义错误,无法进入浏览器启动逻辑。
  • WebDriver版本不匹配:若使用Selenium 4.6以下版本,未手动配置与本地Chrome版本完全匹配的ChromeDriver,也未将驱动路径加入系统环境变量,会直接导致浏览器启动失败。
  • 变量引用错误:close_browser方法内传值时使用的username、password为未定义的局部变量,未指向初始化时赋值的self.username、self.password,浏览器启动后也会触发报错。
  • 方法名与功能不符:命名为close_browser的方法实际承载了登录逻辑,仅作规范建议不影响运行。

修复方案

  1. 升级Selenium到最新版本,内置驱动自动适配能力无需手动配置ChromeDriver:
    pip install --upgrade selenium

  2. 修复后的完整代码如下,同步适配Selenium 4的官方推荐元素查找语法,消除弃用警告:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

class InstagramBot():
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Chrome()
    
    def login_and_close(self):
        self.driver.get("https://www.instagram.com/")
        time.sleep(5)
        name_input = self.driver.find_element(By.NAME, "username")
        name_input.send_keys(self.username)
        time.sleep(2)
        password_input = self.driver.find_element(By.NAME, "password")
        password_input.send_keys(self.password)
        time.sleep(2)
        self.driver.find_element(By.XPATH, '//*[@id="loginForm"]/div/div[3]/button/div').click()
        time.sleep(7)
        self.driver.close()
        self.driver.quit()

# 调用示例
if __name__ == "__main__":
    bot = InstagramBot("替换为你的账号", "替换为你的密码")
    bot.login_and_close()

内容的提问来源于stack exchange,提问作者Рома

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:27:06