pyqt 如何设置 暂停程序 等待 UI输入参数 继续进程

程序为自动登陆百度推广后台,要点在于,截屏裁剪获取验证码图片,显示在UI窗口,然后在窗口手动输入验证码,程序获取验证码,继而登陆。
现在的问题是,找不到好的暂停和继续线程的方法,全都卡死,求大手子指教!

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QMessageBox
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time,os,sys,datetime,re
import pandas as pd,numpy as np
from pandas import DataFrame,Series
from openpyxl import Workbook,load_workbook
from PIL import Image
from PyQt5.QtWidgets import QApplication, QMainWindow
import threading

class Ui_MainWindow(object):

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(532, 229)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(30, 110, 61, 20))
        self.label.setObjectName("label")
        self.lineEdit_1 = QtWidgets.QLineEdit(self.centralwidget)
        self.lineEdit_1.setGeometry(QtCore.QRect(100, 110, 113, 20))
        self.lineEdit_1.setObjectName("lineEdit_1")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(30, 70, 61, 16))
        self.label_5.setObjectName("label_5")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(230, 110, 75, 21))
        self.pushButton_2.setObjectName("pushButton_2")
        self.label_7 = QtWidgets.QLabel(self.centralwidget)
        self.label_7.setGeometry(QtCore.QRect(40, 150, 51, 21))
        self.label_7.setObjectName("label_7")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(60, 20, 158, 23))
        self.pushButton.setObjectName("pushButton")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(93, 150, 301, 31))
        self.label_2.setText("")
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(110, 61, 191, 41))
        self.label_3.setText("")
        self.label_3.setObjectName("label_3")
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "输入验证码"))
        self.label_5.setText(_translate("MainWindow", "获取验证码"))
        self.pushButton_2.setText(_translate("MainWindow", "确定"))
        self.label_7.setText(_translate("MainWindow", "结果"))
        self.pushButton.setText(_translate("MainWindow", "开始生成报表"))

class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        self.setupUi(self)
        self.login = Login(self)
        self.pushButton.clicked.connect(self.on_click1)
        self.pushButton_2.clicked.connect(self.on_click2)

    def on_click1(self):
        self.login.withoutCookieLogin(driver,url_login)

    def on_click2(self):
        authCode = self.lineEdit_1.text()
        #线程继续
        cond.notify()

#登陆后台
class Login(QtCore.QThread):

    def __init__(self,parent=None):
        super(Login,self).__init__(parent)

    def withoutCookieLogin(self,driver,url):
        cond.acquire()
        driver.get(url)
        #等待页面加载
        WebDriverWait(driver,10)
        #点击账号登陆
        driver.find_element_by_xpath('//*[@class=\'login-header\']/span').click()
        driver.find_element_by_xpath('//*[@id=\'uc-login\']/div/div[1]/input').clear()
        driver.find_element_by_xpath('//*[@id=\'uc-login\']/div/div[1]/input').send_keys(username)
        driver.find_element_by_xpath('//*[@id=\'uc-login\']/div/div[2]/div/input[3]').clear()
        driver.find_element_by_xpath('//*[@id=\'uc-login\']/div/div[2]/div/input[3]').send_keys(password)

        while True:
            #获取验证码图片
            driver.save_screenshot("auth_code.png")
            im = Image.open("auth_code.png")
            (x,y,w,h) = (930,300,95,40)
            im_cut = im.crop((x, y, x+w, y+h))
            im_cut.save("auth_code_cut.png")
            png = QtGui.QPixmap('C:/Temp/PythonAnalyse/auth_code_cut.png')
            ui.label_3.setPixmap(png)
            #手动输入验证码
            ui.label_2.setText('请输入验证码')
            #线程挂起
            cond.wait()
            driver.find_element_by_xpath('//*[@id=\'uc-login\']/div/div[3]/input').send_keys(authCode)
            #点击登陆
            driver.find_element_by_xpath('//*[@id=\'uc-login\']/div[2]/input').click()
            time.sleep(1)
            try:
                #判断验证码是否正确
                if driver.current_url == url:
                    print('验证码错误')
                    continue
                else:
                    print('登陆成功')
                    break
            except:
                pass
        return driver

#参数
DIR = 'E:/data/'
username = 'username'     #账户
password = 'password'  #密码

url_login = "http://cas.baidu.com/?tpl=www2&fromu=http%3A%2F%2Fwww2.baidu.com%2F"


authCode = 0
cond = threading.Condition()
options = webdriver.ChromeOptions()
prefs = {"download.default_directory": DIR}
options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=options)

#主程序
app = QApplication(sys.argv)
ui = MainWindow()
ui.show()
sys.exit(app.exec_())






阅读 5.8k
1 个回答
def on_click1(self):
        self.login.withoutCookieLogin(driver,url_login)

这一块耗时太大,并没有开启线程。开启线程的方式如下

import threading
...
...
t = threading.Thread(target=self.login.withoutCookieLogin,args=(driver,url_login))
t.start()

另外说下,pyqt很重要的一个机制是信号与槽,学会如何正确灵活地使用信号与槽,以及pyqt后台开启线程处理耗时操作,使得界面与后端分离,不会卡死UI,这些是pyqt的精髓

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题