Issue
The code provided opens a PyQt5 Window in which the user can start a selenium browser. The problem is that when I close the browser, the main window will close too.
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()
I know that the while loop stopping is causing this but i don't know how to fix it. I've tried to re-open the window after the loop stops but that didn't work.
Solution
Avoid blocking the main event loop caused by the while loop in handleButton
. Instead, use Qt's QTimer
to periodically check if the browser window is open. Customize the timer interval to suit your application's needs.
Answered By - aazizzailani
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.