如何在不影响PyQt5应用程序的情况下使用BeautifulSoup进行Web刮擦



我正在制作一个应用程序,该应用程序涉及访问网站并获取它们拥有的链接(以及图像(,但这些操作需要一些时间,并且会导致应用程序冻结。我曾尝试使用QThreadQRunnable来尝试将应用程序的执行与我使用的函数的执行分离。我在我的应用程序中编程了一个关于它如何工作的小例子:

from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow,QLineEdit,QVBoxLayout
from PyQt5.QtCore import QThread
from bs4 import BeautifulSoup
import requests

class mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(600,64)

## Set a QLineEdit
self.Line=QtWidgets.QLineEdit()
self.Line.setPlaceholderText('You should be able to type here while the links are searched')
self.Line.setFixedSize(600,32)
self.layout().addWidget(self.Line)
## Set a QPushButton
self.Button=QtWidgets.QPushButton()
self.Button.setText('Seach links')
self.Button.move(0,32)
self.Button.setFixedSize(600,32)
self.layout().addWidget(self.Button)
## Connect button with function
self.Button.clicked.connect(lambda:self.search_start())
## Function calls QProcess class
def search_start(self):
self.sclass=search_class()
self.sclass.func_seach()
## Class search for links
class search_class(QThread):
def func_seach(self):
url='https://youtu.be/dQw4w9WgXcQ'
links_list=[]
for link in BeautifulSoup(requests.get(url).text, 'html.parser').find_all('a'):
links_list.append(link.get('href'))
print(links_list)
if __name__=='__main__':
Aplication=QtWidgets.QApplication([])
MainWindow=mainwindow()
MainWindow.show()
Aplication.exec_()

在执行该功能时,如何防止应用程序冻结我想你可能已经注意到了,我对这件事还很陌生。我需要知道哪里出了问题,我做错了什么,以及如何解决。事先非常感谢。

解决方案是将下面的整个类放在第一个类内的一个函数中,并通过线程中启动另一个函数的另一个功能触发我的函数:

from PyQt5 import QtWidgets,QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow,QLineEdit,QVBoxLayout
from PyQt5.QtCore import QThread
from bs4 import BeautifulSoup
import requests

class mainwindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setFixedSize(600,64)
self.Line=QtWidgets.QLineEdit()
self.Line.setPlaceholderText('You should be able to type here while the links are searched')
self.Line.setFixedSize(600,32)
self.layout().addWidget(self.Line)
## Set a QPushButton
self.Button=QtWidgets.QPushButton()
self.Button.setText('Seach links')
self.Button.move(0,32)
self.Button.setFixedSize(600,32)
self.layout().addWidget(self.Button)
## Connect button with function
self.Button.clicked.connect(lambda:self.search_start())
## Function calls func_seach function as a thread
def search_start(self):
thread=Thread(target=self.func_seach)
thread.start()

def func_seach(self):
url='https://youtu.be/dQw4w9WgXcQ'
links_list=[]
for link in BeautifulSoup(requests.get(url).text, 'html.parser').find_all('a'):
links_list.append(link.get('href'))
print(links_list)
if __name__=='__main__':
Aplication=QtWidgets.QApplication([])
MainWindow=mainwindow()
MainWindow.show()
Aplication.exec_()

相关内容

最新更新