Как проанализировать шаблон BeautifulSoup List или Dict to Flask и отобразить вывод на html-страницу? - PullRequest
0 голосов
/ 04 июня 2019

Я новичок в колбе, и я пытаюсь отобразить выходные данные колбы для отображения шаблона на веб-странице 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 ]

1 голос
/ 04 июня 2019

Вы должны добавить инструкцию возврата в if условие:

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

0 голосов
/ 04 июня 2019

вам нужно передать ваши данные в качестве аргумента в render_template() следующим образом:

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

EDIT:

@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')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...