如何解析BeautifulSoup List或Dict到Flask渲染模板并显示输出到html页面?

时间:2019-06-04 09:53:51

标签: python flask beautifulsoup

我是flask的新手,我正尝试显示flask输出以在html网页中呈现模板。我在控制台中获取输出,但未在html页面上显示..如何将此结果表显示到html页面?或执行此操作的任何最佳方法。.我们将不胜感激。.预先感谢

App.py

from flask import Flask, render_template, request,redirect,url_for
from bs4 import BeautifulSoup
import requests
import time
import cgi

app = Flask(__name__)

@app.route('/', methods= ['POST','GET'])
def inputForm():
    if request.method == 'POST':
        STD = request.form['STDCode']
        return redirect(url_for('Search'))

    return render_template('Base.html')

@app.route('/Search', methods= ['POST','GET'])
def Search():
    if request.method == 'POST':
        STD = request.form['STDCode']
        #STD=20
        url = ('http://1min.in/telecom/stdcode/{}'.format(STD))
        response = requests.get(url)
        time.sleep(1)

        soup = BeautifulSoup(response.content, "html.parser")
        Table = soup.find_all('table', class_='table table-bordered')

        Table = Table[0]

        data = []
        for row in Table.find_all('tr'):
            cells = row.find_all('td')
            print(len(row))

            datainfo = {}

            datainfo['State'] = cells[0].find(text=True)
            datainfo['District'] = cells[1].find(text=True)
            datainfo['City'] = cells[2].find(text=True)
            datainfo['STDCode'] = cells[3].find(text=True)
            datainfo['ServiceArea'] = cells[4].find(text=True)
            datainfo['LCDA'] = cells[5].find(text=True)
            datainfo['SDCA'] = cells[6].find(text=True)

            data.append(datainfo)
            print(datainfo)

    return render_template('SearchResult.html')



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

Base.html

<html>
  <head>
    <title>My App</title>
  </head>
  <body>
  <h3>Input Form</h3>

  <div class="well text-center">
    <nav class="navbar navbar-light bg-dark">
        <form method="POST" class="form-inline">
            <input type="search" name="STDCode" placeholder="Enter STD 
  Code" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" 
  type="submit">Search</button>
        </form>
    </nav>
  </div>
 </body>
</html>

SearchResult.html

{% include "Base.html" %}
<div>
    {% block body %}
    <table class="table table-striped" border=1>
            <tr>
                <th>State</th>
                <th>District</th>
                <th>City/Area</th>
                <th>STD Code</th>
                <th>service Area</th>
                <th>LDCA</th>
                <th>SDCA</th>
            </tr>

            {% for key, datainfo in data %}
            <tr>
                <td> {{ datainfo['Name'] }} </td>
                <td> {{ datainfo['District'] }}</td>
                <td> {{ datainfo['City'] }} </td>
                <td> {{ datainfo['STDCode'] }} </td>
                <td> {{ datainfo['ServiceArea'] }} </td>
                <td> {{ datainfo['LCDA'] }} </td>
                <td> {{ datainfo['SDCA'] }} </td>

            </tr>
            {% endfor  %}
    </table>
    {% endblock %}

2 个答案:

答案 0 :(得分:1)

您应该在条件if内添加return语句:

return render_template('SearchResult.html', data=data)

更改app.py文件

@app.route('/Search', methods= ['POST','GET'])
def Search():
    if request.method == 'POST':
        STD = request.form['STDCode']

        url = ('http://1min.in/telecom/stdcode/{}'.format(STD))
        response = requests.get(url)
        time.sleep(1)

        soup = BeautifulSoup(response.content, "html.parser")
        Table = soup.find_all('table', class_='table table-bordered')

        if len(Table) <=0:
            return render_template('Base.html')

        Table = Table[0]

        datainfo = {}
        for row in Table.find_all('tr'):
            key = None
            value = None

            for cell in row.find_all("td"):
                _class = cell.get('class')
                if "td-name" in _class: 
                    key = cell.text.strip()
                elif "td-value" in _class:
                    value = cell.text.strip()

            if key is not None and value is not None:

                if "STD Code" in key:
                    span = row.find("span",{'class':"highlight"})
                    datainfo[key] = span.text.strip()
                else:
                    datainfo[key] = value

        return render_template('SearchResult.html',data=datainfo)

    return render_template('Base.html')

更改SearchResult.html文件

{% include "Base.html" %}
<div>
    {% block body %}
    <table class="table table-striped" border=1>
            <tr>
                <th>State</th>
                <th>District</th>
                <th>City/Area</th>
                <th>STD Code</th>
                <th>service Area</th>
                <th>LDCA</th>
                <th>SDCA</th>
            </tr>

            <tr>
                <td> {{ data['State'] }} </td>
                <td> {{ data['District'] }}</td>
                <td> {{ data['City/Area'] }} </td>
                <td> {{ data['STD Code'] }} </td>
                <td> {{ data['Service Area'] }} </td>
                <td> {{ data['LDCA'] }} </td>
                <td> {{ data['SDCA'] }} </td>

            </tr>

    </table>
    {% endblock %}

enter image description here

答案 1 :(得分:0)

您需要像这样pass your data as argumentrender_template()

return render_template('SearchResult.html', data=data)

编辑:

@app.route('/Search', methods= ['POST','GET'])
def Search():
    data = []
    if request.method == 'POST':
        # your code here, excluding the data = [] line
    return render_template('SearchResult.html', data=data)

@app.route('/Search', methods= ['POST','GET'])
def Search():
    if request.method == 'POST':
        # your code here
        return render_template('SearchResult.html', data=data)
    return render_template('Base.html')