Hello. I wrote a simple parser:

import codecs #Переопределяю кодировку def open(path, mode): return codecs.open(path, mode, 'utf-8') import time from bs4 import BeautifulSoup # Импортирую парсер import requests from PyQt5.QtMultimedia import QMediaPlayer, QMediaContent from PyQt5.QtCore import QUrl, QFileInfo audioFile = r"C:\Users\Grzegorz\PycharmProjects\parser\parser\alert.mp3" player = QMediaPlayer() player.setMedia(QMediaContent(QUrl.fromLocalFile(QFileInfo(audioFile).absoluteFilePath()))) # Для оповещения def parser (site): response = requests.get(site) soup = BeautifulSoup(response.content, "html.parser") # Выгружаю содержимое content = soup.find('div', {"class": "content"}) for row in content.find_all('div', {"class": "entry"}): title = row.find_all('h3', {'class': "entry__title"}) description = row.find_all('div', {"class": "entry__content"})[0].text[:-7] link_beta = str(row.find_all('h3', {'class': "entry__title"}))[35:] a = link_beta.index('"') link = link_beta[:a] photo = row.find('img', {'class': 'wp-post-image'}).attrs["src"] full = (photo[2:] + '\n' + '🌎 ' + title[0].text + '\n' + '📎 ' + description + '\n' + '📌 ' + link + '\n\n') result1 = open("fly4free.txt", "r").readlines() check = str(result1).find(full[:50]) # Проверяю файл на наличие спарсенного текста if check == -1: result1.insert(0, full) result = open("fly4free.txt", "w") for line in result1: result.write(line) result.close() player.play() while True: # Псевдо-автоматизация скрипта parser("http://www.fly4free.pl") parser("http://www.fly4free.com/flights/flight-deals/europe/") time.sleep(5) 

But for some reason, when you start via cmd, you get an error: "QObject :: startTimer: Timers can only be used with threads started with QThread"

Can you please tell me how to fix it?

Thank.

  • In order for Qt objects to work correctly, you must always create QApplication and only after that create the remaining objects. Also, Qt objects will not work unless EventLoop running. That is, message processing will not work for you until you execute the QApplication.exec method. When using Qt, you will not be able to use while True and time.sleep . - Avernial
  • Avernial, I correctly understood that in my case, while True, time.sleep and sound notification with Qt can not be combined? - Grzegorzg
  • Yes exactly. If you use time.sleep , your entire application will freeze for 5 seconds, including playing the sound. Therefore, instead of time.sleep you should use QTimer . And while True will be replaced with QApplication.exec or QCoreApplication . - Avernial

1 answer 1

This error occurs because Qt objects require EventLoop without which they can not work correctly. Therefore, to use these objects, you must create QApplication for a GUI application or QCoreApplication for a console application. after that, you must call the QApplication.exec method, which provides message processing.

Option how to solve the problem:

 from PyQt5 import Qt audioFile = "file.mp3" app = Qt.QCoreApplication([]) player = Qt.QMediaPlayer() player.setMedia(Qt.QMediaContent(Qt.QUrl.fromLocalFile(Qt.QFileInfo(audioFile).absoluteFilePath()))) timer = Qt.QTimer() def on_timer(): print("parse data") parser("http://www.fly4free.pl") parser("http://www.fly4free.com/flights/flight-deals/europe/") timer.timeout.connect(on_timer) timer.start(5000) app.exec() 
  • Avernial, thank you so much, it all worked! - Grzegorzg