每当我在终端中打印出抓取的数据时,它都会很好地显示抓取的数据,但是每当我尝试使用 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>
您应该使用:
return render_template('index.html', head=head, snd_author=snd_author, fst_article=fst_article)