我正在尝试创建一个 youtube scraper 网页(出于教育目的;我永远不会发布它。只是想用它来学习)。我当前拥有的是一个网页,其中有一个文本框,其中包含搜索查询和搜索按钮。当按下搜索按钮时,文本框的内容会通过ajax post请求发送到Python Flask文件(代码如下),我在其中使用一些库在youtube上进行搜索,然后Python文件打印搜索结果结果链接到终端。我希望发生的是将搜索结果显示在我的网页上以供用户阅读,但我一生都无法弄清楚如何让 Flask python 文件将其结果发送到html 页面。
index.html:
<body>
<center>
<span>
<img src="{{ url_for('static', filename='assets/logo.png') }}" style="float: left;" id="logo">
<input type="text" class="textbox" id="searchbar" style="width: 500px; height: 30px">
<button style="height: 30px" onclick="performPost()">Search</button>
</span>
</center>
</body>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script>
function performPost(){
$.ajax({
type: "POST",
url: "{{ url_for('search') }}",
data: {"search" : document.getElementById("searchbar").value},
})
}
</script>
main.py:
import urllib.request
import urllib.parse
import re
from flask import Flask, render_template, request
def searchSite(searchInput):
query_string = urllib.parse.urlencode({"search_query" : searchInput})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'watch\?v=(.{11})', html_content.read().decode())
return (search_results)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', text = "heehee")
@app.route('/index.html', methods=['POST', 'GET']) #NOTE: i just changed this line. It used to say @app.route('/', methods=['POST', 'GET'])
def search():
if request.method == 'POST':
data = request.form
searchQuery = data.getlist('search')[0]
searchResults = searchSite(searchQuery)
searchList = []
for i in range(10):
searchList.append("http://www.youtube.com/watch?v=" + str(searchResults[i]))
print(searchList)
return render_template('index.html', name = "jaaa")
if __name__ == '__main__':
app.run(
host = '127.0.0.1',
port = 5001,
debug = True
)