【问题标题】:how to use scrapy with tkinter smoothly?如何顺利使用scrapy和tkinter?
【发布时间】:2020-12-05 11:53:17
【问题描述】:

我想将 scrapy 与我用 tkinter 制作的 GUI 一起使用,spider 可以单独使用 GUI 正常工作,但是当我使用 GUI 按钮启动 scrapy spider 时,GUI 没有响应,如您在图像中看到的那样.

enter image description here

这是我的代码:

from tkinter import *
import subprocess

class Test():
    def __init__(self):
        self.root = Tk()
        self.root.geometry('300x200')
        self.button = Button(self.root,
                          text = 'Click Me',
                          command=lambda:self.pop_up())
        self.button.pack()
    self.root.mainloop()


def scrape(self):
   process = subprocess.Popen("scrapy runspider url_scraper.py -o output.csv")
   process.wait()

def pop_up(self):
    top = Toplevel()

    btn = Button(top, text="Output filename: ")
    e = Entry(top)
    scrape = Button(top, text="Start", command=lambda: [top.destroy(), self.scrape()])

    btn.grid(row=0, column=0)
    e.grid(row=1, column=1)
    scrape.grid(row=2, column=0)


app = Test()

我只是希望它们在我的刮板刮取数据时不要挂起。请帮我解决这个问题。

提前致谢。

【问题讨论】:

  • process.wait() 将阻止应用程序。
  • 使用线程模块

标签: python-3.x user-interface tkinter web-scraping scrapy


【解决方案1】:

process.wait() 等待进程完成,阻止 GUI 的主循环运行。您可以删除它,或使用threading

from threading import Thread

def threaded_function(arg):
    process = subprocess.Popen("scrapy runspider url_scraper.py -o output.csv")

thread = Thread(target = threaded_function, args = (an_argument, ))
thread.start()

【讨论】:

  • 它正在工作,但你能定义这个:args = (an_argument, )。我如何传递参数并使用它们?我的代码是:def scrape(self, filename): thread = Thread(target=thread_scrape, args=(filename)) thread.start() def thread_scrape(self, filename): process = subprocess.Popen(f"scrapy runspider url_scraper.py -o {filename}.csv"),但它给出了错误:TypeError: thread_scrape() 需要 2 个位置参数,但给出了 5 个
  • args=(filename) 应该是 args=(filename,) 因为 args 应该是一个元组或列表。顺便说一句,使用subprocess.Popen() 时不需要线程。
猜你喜欢
  • 2016-09-27
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-10
相关资源
最近更新 更多