【问题标题】:Why doesn't this html template render the scraped website data in the web browser(Python, Flask, HTML, Web-Scraping)?为什么这个 html 模板没有在 Web 浏览器(Python、Flask、HTML、Web-Scraping)中呈现抓取的网站数据?
【发布时间】:2022-02-18 17:25:43
【问题描述】:

每当我在终端中打印出抓取的数据时,它都会很好地显示抓取的数据,但每当我尝试使用 Python Flask 提供它时,我使用的 HTML 模板不会在 Web 浏览器中呈现数据。如果你能帮我修复这段代码。

Python(Flask)文件:

from flask import Flask, render_template
from bs4 import BeautifulSoup as BS
import requests

src = requests.get('https://webscraper.netlify.app/').text


scraper = BS(src, 'lxml')

# head = scraper.find('main').select_one('article:nth-of-type(4)').div.text
# author = scraper.find('main').select_one('p').text

head = scraper.body.header.h1.text

snd_author = scraper.body.main.select_one('article:nth-of-type(2)').p.text

fst_article = scraper.body.main.article.div


app = Flask(__name__)
@app.route('/')
def index():
    return render_template('index.html', **locals())

app.run(debug=True)

HTML(视图)文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=2.0"/>
    <title>Python Flask Web Scraper</title>
  </head>
  <body>
    <!-- Python Flask Variables go here: -->
    
    <h1> {{ head }} </h1>

    <p>{{ snd_author }}</p>
    
    <article>{{ fst_article }}</article>
    
  </body>
</html>

【问题讨论】:

    标签: python html flask web-scraping


    【解决方案1】:

    你应该改用:

    return render_template('index.html', head=head, snd_author=snd_author, fst_article=fst_article)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-19
      • 2020-11-01
      • 2019-06-08
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      相关资源
      最近更新 更多