python - 无法在 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()
解决方案
通过说global driver
您也可以在第二个函数的第一个函数中使用相同的驱动程序。驱动程序变量在第一个函数中定义,它只保留在第一个函数中,您在第二个函数中使用它的方法,它没有被定义为 nw。所以说global driver
将使它也可用于第二个功能
推荐阅读
- botframework - LUIS 机器人的问题包含撇号/单引号
- node.js - mongoose.Model.updateOne 不适用于嵌套属性查询
- c# - 链接数组属性
- c++ - 查找文本文件中的常用词、顺序错误和计数
- c# - 从另一个文件/类调用非静态方法
- python - 我怎么能用记事本写的东西做一个if语句
- python - 在 Python 中为字段名称添加前缀
- python - Keras CNN:验证数据集不包括所有类时的语法
- android - 为什么openCV4Android的bitmapToMat只支持RGBA_8888和RGB_565?
- r - 如何使用预测功能获取新列