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

2024-04-20 10:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

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

登录之后,我想对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对象并使用它?你知道吗


Tags: andto对象textselfobjectinitdef
1条回答
网友
1楼 · 发布于 2024-04-20 10:33:19

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

相关问题 更多 >