2017-12-05 14 views
0

私はPythonを初めて使い、まだ学習しようとしていますが、この問題を処理できませんでした。無限ループでいくつかの関数(クラスにある)を実行したい。 QApplicationなので、私はQTimerでそれを行うべきであることを学びました。しかし、それを行う方法を模索するときには、私は実際の代替手段を見つけることができませんでした。QTimerを使用してinfinteループで関数を実行する

timer = QTimer() 
timer.timeout.connect(function) 
timer.start(60000) 

しかし、私は私のコードにこれらを挿入するときには違いはありません:一般的なソリューションです。関数、クラスなどの下に挿入しようとしましたが、結果を取得できませんでした。私のループ機能はここにあります:

__author__ = 'pc' 
import requests 
from bs4 import BeautifulSoup 
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets 
import sqlite3 
import sys, getopt, time 
from PyQt5.QtCore import QTimer 

records = [] 
def scrape_page(url, html): 
    soup = BeautifulSoup(html, 'html.parser') 
    data = soup.find('div', class_='tablo_dual_board') 
    try: 
     datas = data.text.splitlines() 
     datas1 = list(filter(None, datas)) 
     records.append(datas1) 
    except: 
     pass 

def process_records(): 
    # add record to database ... 
    print('process records:', len(records)) 

def generate_urls(): 
    onexurl = "https://1xbahis19.com/en/live/Football/" 
    reply = requests.get(onexurl) 
    soup = BeautifulSoup(reply.content, "html.parser") 
    income = soup.find_all("ul", {"id":"games_content"}) 
    links = soup.find_all("a", {"class": "c-events__name"}) 
    urls = [] 
    for matchlink in links: 
     urls.append("https://1xbahis19.com/en/"+(matchlink.get("href"))) 
    return urls 

class WebPage(QtWebEngineWidgets.QWebEnginePage): 
    def __init__(self): 
     super(WebPage, self).__init__() 
     self.loadFinished.connect(self.handleLoadFinished) 

    def start(self, urls): 
     self._urls = iter(urls) 
     self.fetchNext() 

    def fetchNext(self): 
     try: 
      url = next(self._urls) 
     except StopIteration: 
      return False 
     else: 
      self.load(QtCore.QUrl(url)) 
     return True 

    def processCurrentPage(self, html): 
     scrape_page(self.url().toString(), html) 
     if not self.fetchNext(): 
      process_records() 
      print(records) 
      QtWidgets.qApp.quit() 

    def handleLoadFinished(self): 
     self.toHtml(self.processCurrentPage) 

app = QtWidgets.QApplication(sys.argv) 
webpage = WebPage() 
webpage.start(generate_urls()) 
timer = QTimer() 
timer.timeout.connect(WebPage) 
timer.start(60000) 
app.exec_() 

誰でもこの助けてくださいできますか?

+0

どこでタイマーを使用するようになったのですか? – eyllanesc

+0

@eyllanesc私は[ここ](https://stackoverflow.com/questions/25080561/pyqt-application-and-infinite-loop)とstacoverflow投稿から学んだ –

答えて

1

スクレーパーを定期的に実行したいとします。以下のスクリプトは、すべてのURLを60秒に1回掻き集めます。 signal部分は、無限ループを終了させる方法を提供するためのものです。Ctrl + C(つまりKeyboardInterrupt)を実行するとすぐに停止します。

import requests 
from bs4 import BeautifulSoup 
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets 
import sqlite3 
import sys, getopt, time 
from PyQt5.QtCore import QTimer 

import signal 
# press Ctrl+C to stop the script 
signal.signal(signal.SIGINT, signal.SIG_DFL) 

records = [] 
def scrape_page(url, html): 
    print('scraping page:', url) 
    soup = BeautifulSoup(html, 'html.parser') 
    data = soup.find('div', class_='tablo_dual_board') 
    try: 
     datas = data.text.splitlines() 
     datas1 = list(filter(None, datas)) 
     records.append(datas1) 
    except: 
     pass 

def process_records(): 
    # add record to database ... 
    print('processed records:', len(records)) 
    # clear the current records 
    del records[:] 
    # re-run after a timeout 
    QTimer.singleShot(60000, run) 

def run(): 
    print('running scraper...') 
    webpage.start(generate_urls()) 

def generate_urls(): 
    print('generating urls...') 
    onexurl = "https://1xbahis19.com/en/live/Football/" 
    reply = requests.get(onexurl) 
    soup = BeautifulSoup(reply.content, "html.parser") 
    income = soup.find_all("ul", {"id":"games_content"}) 
    links = soup.find_all("a", {"class": "c-events__name"}) 
    urls = [] 
    for matchlink in links: 
     urls.append("https://1xbahis19.com/en/"+(matchlink.get("href"))) 
    return urls 

class WebPage(QtWebEngineWidgets.QWebEnginePage): 
    def __init__(self): 
     super(WebPage, self).__init__() 
     self.loadFinished.connect(self.handleLoadFinished) 

    def start(self, urls): 
     self._urls = iter(urls) 
     self.fetchNext() 

    def fetchNext(self): 
     try: 
      url = next(self._urls) 
     except StopIteration: 
      return False 
     else: 
      self.load(QtCore.QUrl(url)) 
     return True 

    def processCurrentPage(self, html): 
     scrape_page(self.url().toString(), html) 
     if not self.fetchNext(): 
      process_records() 

    def handleLoadFinished(self): 
     self.toHtml(self.processCurrentPage) 

app = QtWidgets.QApplication(sys.argv) 
webpage = WebPage() 
run() 
app.exec_() 
+0

もう一度エコモロありがとう、私は恐れるそれを働かせることはできませんでした。一度は完璧に動作しますが、ループしません。ちなみに私が知っている 'timer.start(60000)'は60秒ではなく60分を意味します。さらに、コードを直接コピーして追加したので、 'run()'を別々に呼び出すと思います。 –

+1

@AhmetUluer。私の更新された答えを見てください。あなたのスクリプトの主な問題は、現在のバッチのURLが処理された後にアプリケーションを終了していた 'processCurrentPage'の行を削除する必要があることでした。 – ekhumoro

+0

何度もありがとう、あなたは私の日々を救った。それは完全に動作します。 –

関連する問題