Selenium全局变量driver设置失败,出现'NoneType'无get属性错误
问题分析
错误核心是全局变量driver未被正确初始化。你在init()函数里创建了driver实例,但这是一个局部变量,并没有修改全局作用域中的driver变量。因此load()函数调用的仍然是初始值为None的全局driver,自然触发'NoneType' object has no attribute 'get'错误。
解决方案
方案1:用global关键字绑定全局变量
在init()函数开头添加global driver,明确告诉Python要修改全局作用域的driver:
def init(): global driver # 声明使用全局变量 subprocess.run("taskkill /f /im msedge.exe") edge_options = EdgeOptions() edge_options.use_chromium = True # 原有配置代码保持不变 path = "user-data-dir="+str(Path.home())+"\\\\AppData\\\\Local\\\\Microsoft\\\\Edge\\\\User Data" print(path) edge_options.add_argument(path); edge_options.add_argument("--profile-directory=Default") edge_options.add_argument("--no-sandbox") edge_options.add_argument("--disable-setuid-sandbox") edge_options.add_argument("--remote-debugging-port=9222") edge_options.add_argument("--disable-dev-shm-using") edge_options.add_argument("--disable-extensions") edge_options.add_argument("--disable-gpu") edge_options.binary_location = "C:\\\\Program Files (x86)\\\\Microsoft\\\\Edge\\\\Application\\\\msedge.exe" driver = Edge(options = edge_options, executable_path = "D:\\\\msedgedriver.exe")
方案2:让init()返回driver实例(更推荐)
避免全局变量带来的耦合问题,改为通过返回值传递driver,代码结构更清晰:
# 移除全局driver变量 # driver = None def init(): subprocess.run("taskkill /f /im msedge.exe") edge_options = EdgeOptions() edge_options.use_chromium = True path = "user-data-dir="+str(Path.home())+"\\\\AppData\\\\Local\\\\Microsoft\\\\Edge\\\\User Data" print(path) edge_options.add_argument(path); edge_options.add_argument("--profile-directory=Default") edge_options.add_argument("--no-sandbox") edge_options.add_argument("--disable-setuid-sandbox") edge_options.add_argument("--remote-debugging-port=9222") edge_options.add_argument("--disable-dev-shm-using") edge_options.add_argument("--disable-extensions") edge_options.add_argument("--disable-gpu") edge_options.binary_location = "C:\\\\Program Files (x86)\\\\Microsoft\\\\Edge\\\\Application\\\\msedge.exe" return Edge(options = edge_options, executable_path = "D:\\\\msedgedriver.exe") # 返回driver实例 def load(driver): # 接收driver参数 driver.get("https://www.google.com") time.sleep(5) def close(driver): # 接收driver参数 driver.quit() def main(): driver = init() # 接收返回的driver实例 load(driver) close(driver) if __name__ == "__main__": main()
补充提示
- 方案2规避了全局变量的潜在风险(比如变量被意外篡改、代码依赖混乱),是更规范的工程写法。
subprocess.run("taskkill /f /im msedge.exe")会强制关闭所有Edge窗口,使用前确认是否符合你的操作需求。
内容的提问来源于stack exchange,提问作者Mich
相关产品推荐
相关产品推荐

