我对Ajax和Flask完全陌生。我正在尝试使用Flask部署一个Web应用程序,当在HTML页面上单击按钮时,该应用程序将显示Python中抓取的列表中的一些数据(这就是我使用Flask的原因)。我也可能已经将这个问题的标题定为“为什么我的Flask应用程序不起作用?”,好像我尝试加载app.py
文件时遇到了Flask错误。但是,当我运行index.html
页面并单击我的按钮时,我得到
jquery.min.js:2 POST http://127.0.0.1:5500/_get_data/ 405(不允许使用方法)
我已经打印了我要返回的内容,只是为了确保它显示为列表,并且确实如此。在初始化Flask应用程序之前,我还尝试过对文件进行所有刮擦,因为这可能是某种非法刮擦之类的东西。
index.html文件
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>NBA Data Web App</title>
<script src = "http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" crossorigin = "anonymous"></script>
</head>
<body>
<button id = "searchBtn"> Search </button>
<div id = "response"></div>
<script type = "text/javascript">
$('button#searchBtn').click(function() {
$.ajax({
url: "/_get_data/",
type: "POST",
success: function(resp) {
$('div#response').append(resp.data);
}
});
});
</script>
</body>
</html>
app.py文件
#Import dependencies
from flask import Flask, render_template, jsonify
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
import pandas as pd
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/_get_data/', methods = ['POST'])
def _get_data():
#URL of the page we want to scrape (2019-2020 per game player stats)
url = "https://www.basketball-reference.com/leagues/NBA_2020_per_game.html"
#HTML from our URL
html = urlopen(url)
#Convert that HTML into an object
soup = bs(html, 'html.parser')
#Use findall() to get our headers
soup.findAll('tr', limit = 2)
#Extract the text so we can make a list
headers = [th.getText() for th in soup.findAll('tr', limit = 2)[0].findAll('th')]
#Exclude the first column, as we don't care about the ranking order from Basketball Reference
headers = headers[1:]
#Ignore the first header row
rows = soup.findAll('tr')[1:]
#Get the player's stats
player_stats = [[td.getText() for td in rows[i].findAll('td')]for i in range(len(rows))]
stats = pd.DataFrame(player_stats, columns = headers)
stats.head(10)
#Convert our search data to a list for Ajax/Flask
playerData = (stats[stats['Player'] == 'James Harden']).values.tolist()
dataList = ( ", ".join( repr(x) for x in playerData))
return jsonify({'data': render_template('response.html', dataList = dataList)})
if __name__ == "__main__":
app.run(debug = True)
response.html文件(不确定是否与我的错误有关)
<ul>
{% for elem in dataList %}
<li>{{elem}}</li>
{% endfor %}
</ul>