繁体   English   中英

PyQT:如何将Webdriver对象从QThread传递到UI线程?

[英]PyQT : How to pass a webdriver object from QThread to UI thread?

我正在制作一个程序,该程序可以自动进入网站并登录(基本上使用selenium和chrome webdriver)。 用户可以在对话框(使用PyQt4模块)中键入自己的信息(id&pw)和站点地址。 完成后,按确定按钮将执行它。

登录后,我想对该webdriver对象执行其他一些操作。

所以我的问题是,如何将webdriver对象传递给主线程(此处为UI线程),以便我可以执行其他一些操作(例如注销等),或者如何管理以其他方式生成的webdriver对象主线程中的线程?

我正在使用Python3.7.4和PyQt4版本。

我用谷歌搜索类似的问题,发现它可能与信号插槽有关。 因此,我尝试模仿使用自定义信号的此示例( https://nikolak.com/pyqt-threading-tutorial/ )。 在此示例中,它将QString实例传递给主线程(UI线程)。 所以我试图通过模仿它来传递我的webdriver对象,但是进展并不顺利...

代码的基本结构如下:

class MyDialog(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        # and some codes with widget layouts

    def btnOkClicked(self):
        a = [self.editSite1.text(), self.editId.text(), self.editPw.text()]

        self.gothread = goWebsiteThread(a)
        # 'goWebsiteThread' is a thread that generates webdriver object and executes login function

        self.connect(self.gothread, SIGNAL("add_driver(PyQt_PyObject)"), self.add_driver)
        # this line is what I tried to pass the driver object to this main thread

        self.gothread.start()


class goWebsiteThread(QThread, QObject):
# I tried to pass this class's object by making this class inherit QObject class... sorry for unfounded try..

    def __init__(self, sites):
        QThread.__init__(self)
        self.sites = sites

    def goWebsite(self):
        self.driver = webdriver.Chrome('./chromedriver.exe', options=options)
        self.driver.get(some site address that user typed)
        # and codes to log in

        self.emit(SIGNAL('add_driver(PyQt.PyObject)'), self.driver)
        # I tried to pass the driver object by emitting signal...

    def run(self):
    self.goWebsite()

但这不起作用(MyDialog对象无法识别驱动程序对象)。

如何正确地将webdriver对象传递给MyDialog对象并使用它?

Webdriver应该在新线程上运行,并且不可能从UI线程控制Webdriver。 但是您仍然可以将webdriver存储为UI实例的成员变量。 如果要向WebDriver发送一些命令,则需要启动一个新线程并处理新创建的线程中的自动化工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM