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

Python Selenium WebDriver按需启动问题:点击Start按钮启动后调用web_test函数提示'name 'web_driver' is not defined'

Fixing "name 'web_driver' is not defined" Error When Using Selenium with Tkinter

Hey there! Let's break down why you're running into that error and how to fix it so you can launch Selenium only when clicking the "Start" button.

The Root Cause

The problem boils down to variable scope. When you define web_driver inside the start_webdriver() function, it’s a local variable—meaning it only exists inside that function. The web_test() and stop_webdriver() functions can’t access it because it’s not in their scope.

When you uncomment the initial web_driver = webdriver.Edge(...) line, you create a global variable that all functions can see, which is why it works. But we don’t want to launch the driver upfront—we want it on demand.

Solution 1: Use Global Variables (Quick Fix)

You can explicitly tell your functions to use the global web_driver variable with the global keyword. We’ll also add checks to avoid errors if the driver isn’t started yet:

from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Initialize global variable as None
web_driver = None

def start_webdriver():
    global web_driver  # Declare we're using the global variable
    if not web_driver:  # Avoid starting multiple instances
        web_driver = webdriver.Edge('msedgedriver.exe')

def stop_webdriver():
    global web_driver
    if web_driver:  # Only quit if driver exists
        web_driver.quit()
        web_driver = None  # Reset to None for future use

def web_test():
    global web_driver
    if web_driver:  # Ensure driver is started before testing
        web_driver.get('https://stackoverflow.com/')
        web_driver.find_element_by_name('q').send_keys('python selenium')
        web_driver.find_element_by_name('q').send_keys(Keys.ENTER)

CanvasWd = 500
CanvasHg = 300
root = Tk()
root.title("app")
root.geometry(f"{CanvasWd}x{CanvasHg}")
canvas0 = Canvas(root,highlightthickness=0,width=CanvasWd,height=CanvasHg)
web_start_btn = Button(root,text='Start',command=start_webdriver)
web_stop_btn = Button(canvas0,text='Stop',command=stop_webdriver)
web_test_btn = Button(canvas0,text='testing',command=web_test)
canvas0.create_window(30, 10, anchor=NW, window=web_start_btn)
canvas0.create_window(10, 45, anchor=NW, window=web_stop_btn)
canvas0.create_window(90, 45, anchor=NW, window=web_test_btn)
canvas0.grid(row=1, column=1)
root.mainloop()

What Changed:

  • We initialized web_driver as a global variable set to None
  • Added global web_driver in each function to reference the global variable
  • Added checks (if web_driver:) to prevent errors if the driver isn’t running

Solution 2: Use a Class (Cleaner, Scalable Approach)

For better code organization and to avoid global variables, wrap the WebDriver logic in a class. This keeps everything related to the driver in one place:

from tkinter import *
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class WebDriverController:
    def __init__(self):
        self.web_driver = None  # Store driver instance as a class attribute

    def start(self):
        if not self.web_driver:
            self.web_driver = webdriver.Edge('msedgedriver.exe')

    def stop(self):
        if self.web_driver:
            self.web_driver.quit()
            self.web_driver = None

    def run_test(self):
        if self.web_driver:
            self.web_driver.get('https://stackoverflow.com/')
            self.web_driver.find_element_by_name('q').send_keys('python selenium')
            self.web_driver.find_element_by_name('q').send_keys(Keys.ENTER)

# Initialize Tkinter app
CanvasWd = 500
CanvasHg = 300
root = Tk()
root.title("app")
root.geometry(f"{CanvasWd}x{CanvasHg}")
canvas0 = Canvas(root,highlightthickness=0,width=CanvasWd,height=CanvasHg)

# Create controller instance
driver_controller = WebDriverController()

# Bind buttons to controller methods
web_start_btn = Button(root,text='Start',command=driver_controller.start)
web_stop_btn = Button(canvas0,text='Stop',command=driver_controller.stop)
web_test_btn = Button(canvas0,text='testing',command=driver_controller.run_test)

canvas0.create_window(30, 10, anchor=NW, window=web_start_btn)
canvas0.create_window(10, 45, anchor=NW, window=web_stop_btn)
canvas0.create_window(90, 45, anchor=NW, window=web_test_btn)
canvas0.grid(row=1, column=1)
root.mainloop()

Why This Is Better:

  • No messy global variables—all driver logic is encapsulated in the class
  • Easier to add more features (like multiple tests, status checks) later
  • Clearer ownership of the WebDriver instance

Either solution will fix your error, but the class approach is more maintainable for larger apps.

内容的提问来源于stack exchange,提问作者ZOUHAIRI Fouad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:47:37