我正在制作一个网站,我想要这个计数器
#---------------------------------------------- scarper.py
# ... rest of the code
counter = 0
while True:
counter += 1
print(f'Extracting infromation from page: {counter}')
#... rest of the code
显示在我的网站(而不是控制台日志)上的这两个按钮之间。我怎样才能实现这个目标?
#---------------------------------------------- scrape.html
#... rest of the code
<button type="submit" class="btn btn-primary">Start Scraping</button>
<a href="{{ url_for('view_database') }}" class="btn btn-info">View Database</a>
#... rest of the code
该路线的代码如下:
@app.route('/scrape', methods=['GET', 'POST'])
def scrape():
form = ScrapingForm()
if form.validate_on_submit():
city = request.form.get('city')
subregion = request.form.get('subregion')
apart_or_house = request.form.get('apart_or_house')
words_to_check = request.form.get('words_to_check') # Retrieve words to check input
if city and apart_or_house:
g.scraping_finished = False
threading.Thread(target=run_scraper, args=(city, subregion, apart_or_house, words_to_check)).start()
flash('Scraping started!', 'success')
else:
flash('Please fill all required fields.', 'error')
if g.get('scraping_finished', False):
flash('Scraper has finished!', 'info')
return render_template('scrape.html', form=form)
一种解决方案是使用 SSR 并在客户端上创建事件。
添加一个元素以在 scrape.html 中显示计数器值:
<button type="submit" class="btn btn-primary">Start Scraping</button>
<span id="counter">0</span>
<a href="/" class="btn btn-info">View Database</a>
<script>
var source = new EventSource("{{ url_for('scrape') }}");
source.onmessage = function(event) {
document.getElementById('counter').innerHTML = event.data;
};
</script>
将 scrape.py 更改为:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-for-csrf'
class ScrapingForm(FlaskForm):
city = StringField('City', validators=[DataRequired()])
subregion = StringField('Subregion')
apart_or_house = SelectField('Apartment or House', choices=[('apartment', 'Apartment'), ('house', 'House')],
validators=[DataRequired()])
words_to_check = StringField('Words to Check')
submit = SubmitField('Start Scraping')
def run_scraper(city, subregion, apart_or_house, words_to_check):
counter = 0
while True:
counter += 1
print(f'Extracting information from page: {counter}')
yield f'data: {counter}\n\n'
@app.route('/', methods=['GET', 'POST'])
def scrape():
form = ScrapingForm()
if form.validate_on_submit():
city = request.form.get('city')
subregion = request.form.get('subregion')
apart_or_house = request.form.get('apart_or_house')
words_to_check = request.form.get('words_to_check')
if city and apart_or_house:
return Response(stream_with_context(run_scraper(city, subregion, apart_or_house, words_to_check)),
mimetype='text/event-stream')
else:
flash('Please fill all required fields.', 'error')
return render_template('scrape.html', form=form)
if __name__ == '__main__':
app.run(debug=True)
我还将线程替换为stream_with_context,并删除了
g
。
计数器值于 document.getElementById('counter').innerHTML = event.data
更新。