简体   繁体   中英

How do I display the results of a python script in html web page?

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%3DF?p=GC%3DF'
    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>

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%3DF?p=GC%3DF'
    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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM