首页 > 解决方案 > 无法在 Tkinter 中使用两个不同的按钮在我从 Python 中的 Selenium 打开的同一个 chrome 窗口上执行任务

问题描述

Selenium 驱动程序正在我的第一个按钮中工作,但是当我单击尝试使用 selenium 驱动程序调用活动窗口的第二个按钮时,它不起作用。它说驱动程序未定义。这个问题有什么解决办法吗?这样我就可以使用上一个按钮单击驱动程序打开的窗口来执行其他功能。

def myTask1():   
    driver = webdriver.Chrome(executable_path)
    driver.get("#any website")
    #login to any website using username and password then keep that window open
    window_before = driver.window_handles[0]
    window_before_title = driver.title

button_text1 = StringVar()    
button1 = Button(root,textvariable = button_text1,text="Click me", padx=8, pady=8, width="20", command=myTask1)
button_text1.set("Open the Website")
button1.place(relx=.48, rely=.3, anchor=CENTER) 
   
def myTask2():   
    driver.switch_to.window(window_before)
    #main selenium function to perform


button_text2 = StringVar()    
button2 = Button(root,textvariable = button_text2,text="Click me",padx=8, pady=8, width="20", command=myTask2)
button_text2.set("perform function ")
button2.place(relx=.48, rely=.6, anchor=CENTER)

root.mainloop()

标签: pythonseleniumselenium-webdrivertkinterselenium-chromedriver

解决方案


通过说global driver您也可以在第二个函数的第一个函数中使用相同的驱动程序。驱动程序变量在第一个函数中定义,它只保留在第一个函数中,您在第二个函数中使用它的方法,它没有被定义为 nw。所以说global driver将使它也可用于第二个功能


推荐阅读