如何在django中运行web抓取脚本?服务器没有启动

sqougxex  于 2021-08-20  发布在  Java
关注(0)|答案(1)|浏览(304)

我有一个用beautifulsoup4写的网页抓取脚本。脚本应该在600秒后检索信息。现在,我的应用程序没有启动。
我正在从中调用脚本 urls.py ```
from django.urls import path
from details.task import scrape

urlpatterns = [
...
]
scrape()
`task.py`
import time
from details.scrape import ScrapeFunction

def scrape():
ScrapeFunction()
time.sleep(600)
scrape()

必须在应用程序启动后立即调用脚本。
xnifntxz

xnifntxz1#

你的应用程序没有启动,因为你的函数没有退出点。当您启动服务器时,它会陷入无限循环。您可以在这里使用线程。
您的代码应该如下所示: urls.py ```
from django.urls import path
from details.task import scrape
import threading

urlpatterns = [
...
]

threading.Thread(target=scrape, daemon=True).start()
`task.py`
import time
import threading
from details.scrape import ScrapeFunction

def scrape():
threading.Thread(target=ScrapeFunction, daemon=True).start()
time.sleep(600)
scrape()

你应该看看这里。

相关问题