[英]Executing python script using laravel
我正在使用 Laravel 控制台命令來執行 python 腳本。
這就是我在 Laravel 控制台命令文件中的內容:
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
public function handle()
{
$process = new Process(['python', 'App/Console/Python/Main.py']);
$process->run();
// executes after the command finishes
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$this->line($process->getOutput());
}
這就是我在 Main.py 中的內容:
import YellScraper
scraper = YellScraper.Scraper()
scraper.setKeyword('Restaurant')
scraper.setLocation('Burnley')
scraper.start()
print('Done... Exiting')
這就是我在 YellScraper.py 中的內容:
import urllib
import time
import sys
from bs4 import BeautifulSoup
class Scraper:
pages = []
keyword = ""
location = ""
results = []
def setKeyword(self,keywordInput):
self.keyword = keywordInput
def setLocation(self,locationInput):
self.location = locationInput
def createPages(self):
if self.keyword != "" and self.location != "":
for i in range(1,10):
page = 'http://www.yell.com/ucs/UcsSearchAction.do?keywords='+self.keyword+'&location='+self.location+'&pageNum=%s' % i
self.pages.append(page)
else:
print ("Location or Keyword not set\nUse setKeyword or setLocation functions before continuing")
sys.exit(0)
def start(self):
self.createPages()
if self.pages:
for page in self.pages:
f = urllib.urlopen(page)
f = f.read()
soup = BeautifulSoup(f)
listings = soup.find_all("div", class_="parentListing")
if len(listings) > 0:
for listing in listings:
company = {}
#name
company['name'] = listing.find('a', itemprop="name").get_text(strip=True)
#number
company['number'] = listing.select('.l-telephone ul li strong')[0].string
#address
company['address'] = listing.find('span', itemprop="streetAddress").get_text(strip=True) + ' ' + listing.find('span', itemprop="addressLocality").get_text(strip=True) + ', ' + listing.find('span', itemprop="postalCode").get_text(strip=True)
#add company
self.results.append(company)
#keep yell.com happy
time.sleep(15)
return self.results
每當我執行此操作時,我都會收到一條錯誤消息,指出最大執行時間為 60 秒。 我相信 Main.py 不知道 YellScraper 是什么,但不知道如何讓它工作
您似乎想按時運行此 python 腳本,並在完成后獲取 laravel 應用程序的更新。
在這種情況下,我不會從 laravel 運行 python 腳本,而是設置 python 腳本的 cronjob/窗口調度。
After the python script is complete, trigger an API call to the laravel app to update the necessary information so that your application will be decoupled and not rely on other app's executing time range or the library and will only communicate via API interface.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.