2017-01-04 7 views
0

"Open Input File"と "Run"という2つのボタンがあるguiをビルドしたいと考えています。ユーザーが「入力ファイルを開く」をクリックすると、自分のコンピュータからURLを含む1つの列を持つファイルを選択することができます。その人が「実行」をクリックすると、入力ファイルのURLをstart_urls(例:https://doc.scrapy.org/en/latest/topics/spiders.html)として使用する、治療に基づくスクリプトが初期化されます。オブジェクトの開始時に引数をクラスに渡す方法は?

私のスクリプトは次のようになります。

import scrapy 
import sys 
from PyQt5 import QtCore, QtGui, QtWidgets 
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog 
from scrapy.crawler import CrawlerProcess 
file = "Empty" 

class MySpider(scrapy.Spider): 
    global file 
    name = "scriptTest" #name of spider 
    allowed_domains = ["web"] #where is spider allowed to crawl 
    start_urls = [file] #where will spider crawl 

    def parse(self): #scrapes start_urls according to instructions and returns results 

class MyGui(object): #gives description of class type MyGui 
    filename = 'Empty' 
    file = [] 
    def setupUI(self): #describes how base form of gui will look 

    def buttons(self): #creates buttons and connects functions to those buttons 
     self.pushButton.setText(_translate("MainWindow", "Open Input File:")) #creates button with text 
     self.pushButton.clicked.connect(self.showDialog) #connects button one to function showDialog 
     self.pushButton_2.setText(_translate("MainWindow", "Run")) #creates button2 with text 
     self.pushButton_2.clicked.connect(self.runSpider) #connects button two to function runSpider 

    def showDialog(self): #opens QFileDialog and sets global file to name of selected file 

    def runSpider(self): #should start crawling urls from selected file 
     global file 
     global filename 

     def getUrls(filename): #returns first column containing urls (given by gui user in showDialog) as array. 

     file = getUrls() #sets global variable file as returned value of getExcelData 
     process = CrawlerProcess() #creates object 'process' that is of type 'Crawlerprocess' 
     process.crawl(MySpider) #starts crawling 
     process.start() # the script will block here until the crawling is finished 

app = QApplication(sys.argv) 
window = QMainWindow() 

ui = MyGui() #creates object called 'ui' of type 'MyGui 
ui.setupUi(window) #launches gui window 

私が言ったように、私はクモのためのstart_urlsとしてプッシュボタンをクリックした後に、選択したファイルからURLを使いたいです。しかし、「実行」をクリックすると、スパイダーはグローバル変数ファイルの新しい値を使用する代わりに、start_urlsとして「空」の値を使用します。私は理由を理解していると思います。クラスはオブジェクトの記述なので、オブジェクトが初期化されると、記述されたクラスのプロパティを持ちます。

私のようなもので、問題を解決しようとしました:

class MySpider: 
    def __init__(self, arg): 
    self.arg = arg 

しかし、私は解決策を見つけていません。

Q:ユーザーが選択したファイルをMySpiderクラスに渡すにはどうすればよいですか?

私は間違った何かを言っている場合は事前におねがいします! (申し訳ありませんが、私のコードが本当に乱雑/不明な場合、私はまだたくさんのことを学んでいます。)fileを更新すると、

答えて

1

start_urls = [file]は更新されません。以前の参照fileを保持しています。

迅速な回避策(私はよりよい解決策が存在していると確信して)直接start_urlsクラス変数を更新するために、次のようになります。

MySpider.start_urls = getUrls() 
process.crawl(MySpider) #starts crawling 

利点は、あなたはもう

グローバル file変数を必要としないということです
関連する問題