[英]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.