提供的代码打开一个PyQt5窗口,用户可以在其中启动selenium浏览器。问题是,当我关闭浏览器时,主窗口也会关闭。
test.py
from PyQt5 import QtWidgets
from selenium import webdriver
import sys, json
def isRunning(driver):
try:
driver.window_handles
return True
except Exception:
return False
def handleButton2():
print("test")
app = QtWidgets.QApplication(sys.argv)
def handleButton():
profile = webdriver.FirefoxProfile('selenium')
driver = webdriver.Firefox(profile)
driver.get('https://duckduckgo.com/')
logs = []
curr = ''
while isRunning(driver):
if curr != driver.current_url:
logs = []
curr = driver.current_url
log = driver.execute_script(
"return window.performance.getEntries();")
for x in log:
if x not in logs:
logs.append(x)
s = str(x).replace("'", '"')
s = s.replace(': "', ': ').replace('", ', ', ')
s = s.replace(': ', ': "').replace(', ', '", ')
s = s.replace('"}', '}').replace('}', '"}')
s = s.replace(': "[', ': [').replace(': "{', ': {')
s = s.replace(']"', ']').replace('}"', '}')
print(s)
url = json.loads(s)['name']
if url.startswith('http'):
print(url)
app.processEvents() # VERY important
class Window(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.button = QtWidgets.QPushButton('Test')
self.button.clicked.connect(handleButton)
self.button2 = QtWidgets.QPushButton('Test2')
self.button2.clicked.connect(handleButton2)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.button)
layout.addWidget(self.button2)
def mainGUI():
window = Window()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
mainGUI()
字符串
我知道while循环停止是导致这个问题的原因,但我不知道如何修复它。我试图在循环停止后重新打开窗口,但没有工作。
1条答案
按热度按时间wwodge7n1#
避免阻塞由
handleButton
中的while循环引起的主事件循环。相反,使用Qt的QTimer
定期检查浏览器窗口是否打开。自定义计时器间隔以满足应用程序的需要。