使用Python类编写的Selenium程序无法启动、web驱动打不开问题咨询
问题原因
- 缺失必要模块导入语句:未导入
selenium.webdriver、time模块,运行直接触发未定义错误,无法进入浏览器启动逻辑。 - WebDriver版本不匹配:若使用Selenium 4.6以下版本,未手动配置与本地Chrome版本完全匹配的ChromeDriver,也未将驱动路径加入系统环境变量,会直接导致浏览器启动失败。
- 变量引用错误:
close_browser方法内传值时使用的username、password为未定义的局部变量,未指向初始化时赋值的self.username、self.password,浏览器启动后也会触发报错。 - 方法名与功能不符:命名为
close_browser的方法实际承载了登录逻辑,仅作规范建议不影响运行。
修复方案
升级Selenium到最新版本,内置驱动自动适配能力无需手动配置ChromeDriver:
pip install --upgrade selenium修复后的完整代码如下,同步适配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,提问作者Рома
相关产品推荐
相关产品推荐

