LoginSignup
8
14

More than 3 years have passed since last update.

Flaskを使用し、外部ファイルを実行する

Last updated at Posted at 2020-05-29

やったこと

Flaskでウェブページを作成。

ボタンをクリックすると外部のスクレイピングファイルを実行させる。

Flaskの準備

Flaskのインストール

pip install Flask

元となるファイルを作成

root.py
from flask import Flask

app = Flask(__name__)


@app.route('/')
def hello():
    return 'Hello!'


if __name__ == "__main__":
    app.run(debug=True)

実行

python root.py

その後

 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

と、出力されるのでhttp://127.0.0.1:5000/ へアクセスします。

スクリーンショット (57).png

Hello!が表示されています。

テンプレートエンジン「Jinja2」を使ってHTMLを書く

import等追加する

root.py
# from flask import Flask
# 追加↓
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello():
  #return 'Hello!'
  # 追加↓
  return render_template('layout.html', title='Scraping App')


if __name__ == "__main__":
    app.run(debug=True)

templatesフォルダを作成し、その中にlayout.htmlを作ります。
buttonタグをクリックすることでGETメソッドを送信するようにします。

layout.html
<!doctype html>
<html>

<head>
  <!--       ↓ render_templateの中で書いたtitleが入る      --> 
  <title>{{ title }}</title>
</head>

<body>
  <div class="member">
    <img src="/static/img/akimoto.jpg" alt="img1">
    <h2>秋元真夏</h2>
    <form method="GET" action="/scraping">
      <button type="submit">Start Scraping</button>
    </form>
  </div>
</body>

</html>

staticフォルダを作成し、中にcss、img作成し、見た目を整える。

最終的なファイル中身

root.py
from flask import Flask, render_template
# ↓ Flaskを通し実行したいファイルをインポート
import scraping

app = Flask(__name__)


@app.route('/')
def hello():
    return render_template('layout.html', title='Scraping App')

# ↓ /scrapingをGETメソッドで受け取った時の処理
@app.route('/scraping')
def get():
    # ↓ 実行したいファイルの関数
    return scraping.scraping()


if __name__ == "__main__":
    app.run(debug=True)

layout.html
<!doctype html>
<html>

<head>
  <title>{{ title }}</title>
  <link rel="stylesheet" href="/static/css/index.css">
</head>

<body>
  <div class="member">
    <img src="/static/img/akimoto.jpg" alt="img1">
    <h2>秋元真夏</h2>
    <form method="GET" action="/scraping">
      <button type="submit">Start Scraping</button>
    </form>
  </div>
</body>

</html>

↓ 今回実行したスクレイピングファイル
乃木坂46ブログの画像をスクレイピングで取得する

最終のフォルダ構成

  • /root.py
  • /scraping.py
  • /templates
    • layout.html
  • /static
    • /css
      • /index.css
    • /img
      • /akimoto.jpg

表示画面

スクリーンショット (55).png

ボタンをクリック後、作成されたフォルダ

スクリーンショット (56).png

これまでコンソールから実行していたPythonファイルをウェブページを通して行えるようになりました!

8
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
14