flaskを使用した並列のスクレイピングプログラムが途中で止まってしまう

実現したいこと

flaskを使用して特定のページでの動作を自動化したい
並列化しないで平文の場合は問題なく動くのだが、サーバ内で並列処理を行うと途中で処理が終了してしまう
(処理でエラーを吐くわけではなく、タイムアウトになってしまう)

前提

さくらのVPSでubuntuのサーバ内にflaskのアプリケーションを構築して特定のページのスクレイピングを行っています。

発生している問題・エラーメッセージ

アプリ化しないで通常のpythonコードとしてサーバ内で実行してもエラーを吐かないのですが、
API化して並列実行するとタイムアウトエラーが起きてしまいます。
サーバのスペック的にも問題はないと思うので解決方法を教えてほしいです。

該当のソースコード

python

1import time 2import json 3import queue 4import requests 5import concurrent.futures 6from flask import Flask, request, jsonify 7from multiprocessing import Pool, Manager 8from selenium import webdriver 9from selenium.webdriver.common.by import By 10from selenium.webdriver.support.ui import WebDriverWait 11from selenium.webdriver.support import expected_conditions as EC 12from selenium.common.exceptions import TimeoutException 13 14 15@app.route('/sample_api', methods=["POST"])16def sample_api():17 data = request.get_json(force=True)18 19 with Pool(4) as p:20 p.map(mult_task, data)21 22 return 'OK'23 24 25def mult_task(req):26 options = webdriver.ChromeOptions()27 UA = 'Sample'28 options.add_argument('--headless')29 options.add_argument('--user-agent=' + UA)30 options.add_argument('--no-sandbox')31 options.add_argument('--disable-gpu')32 options.add_argument('--disable-popup-blocking')33 34 driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', options=options)35 driver.set_window_size(1200, 1000)36 wait = WebDriverWait(driver=driver, timeout=240)37 38 retries = 039 40 while retries < 3:41 err_postion = 042 try:43 driver.get('https://www.sample.com')44 45 app.logger.error('成功')46 driver.close()47 break48 49 except Exception as e:50 # If an error occurs, increment the retry counter and try again51 retries += 152 if retries == 3:53 driver.close()54 app.logger.error(err_postion)55 app.logger.error(f"Failed to process request after 3 attempts. Error: {e}")56 else:57 app.logger.error(err_postion)58 continue59 60 return 'OK'

試したこと

サーバのスペックは4Core, RAM4GBです。
他に必要な情報があればコメントしていただければ追記いたしますのでよろしくお願いいたします。

コメントを投稿

0 コメント