Home > Software design >  How do I display the results of a python script in html web page?
How do I display the results of a python script in html web page?

Time:03-14

Hello I am new to coding in general. I wanted to create a little project so that I can track the price of gold in a web application through Flask and Python.

The html code just shows a button, when pressed it goes to a new route and there it shows the gold price. The html code of the first route I can style with no problem through the css file. How can I style the second route? Because if I execute everything it just shows the price as intended in upper left corner of the browser. So how can connect a css file to this return value?

This is my python code that I use to find the price and display in the browser.

from flask import Flask, render_template, request

from bs4 import BeautifulSoup
import requests

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/goudprijs")
def priceTracker():
    url = 'https://finance.yahoo.com/quote/GC=F?p=GC=F'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'lxml')
    price = soup.find_all('div', {'class':'D(ib) Mend(20px)'})[0].find('fin-streamer').text
    return(price)

Below you can find my html code:

<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
      <title> Gold tracker</title>
      <link rel="stylesheet" href="{{url_for('static', filename='css/main.css')}}">
  </head>
  <body>

    <p>GOLD TRACKER</p>
    <br>
      <form action="goudprijs" method="get">
          <p> Whats the price?</p>
          <br>
          <input type="submit" value="Update" id="buttonprijs">
      </form>
  </body>
</html>

CodePudding user response:

Use render_template and assign your variable price then in your html code insert {{ variable_name }} in this case {{ price }}

from flask import Flask, render_template, request
from bs4 import BeautifulSoup
import requests

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/goudprijs")
def priceTracker():
    url = 'https://finance.yahoo.com/quote/GC=F?p=GC=F'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'lxml')
    price = soup.find_all('div', {'class':'D(ib) Mend(20px)'})[0].find('fin-streamer').text
    return render_template('goudprijs.html', price=price)
<!DOCTYPE html>
<html>
  <head>
      <meta charset="utf-8">
      <title> Gold tracker</title>
      <link rel="stylesheet" href="{{url_for('static', filename='css/main.css')}}">
  </head>
  <body>

    <p>GOLD TRACKER</p>
    <br>
      <form action="goudprijs" method="get">
          <p> Whats the price?</p>
          <br>
          <p><h4>Price : <h4/> {{ price }}

          <input type="submit" value="Update" id="buttonprijs">
      </form>
  </body>
</html>
  • Related