I'm new in python and flask, and I'm building a web scraper app using Python3 and Flask. But I have a problem with this error: "UnboundLocalError: local variable 'price' referenced before assignment". I don't know what I did wrong in the program to get this error .
I tried 'global a' with initial variable 'a = 0' and wrote the code, but it displays the initial variable only '0' without any change even I changed the URL.
Here is app.py:
# Import Packages
from flask import Flask, render_template, request, url_for
from bs4 import BeautifulSoup
import requests
app = Flask(__name__)
price = 0 # Initial variable or default variable for global variable
@app.route("/", methods=['GET', 'POST'])
def HomePage():
url = request.form.get('asin')
try:
res = requests.get(url)
soup = BeautifulSoup(res.text, 'html.parser')
# Here is I updated it to set the 'price' variable to be global
global price
print(price)
# Check the price location on the page
price = soup.select_one("#priceblock_ourprice").text
except:
pass
return render_template('home.html', url=url, price=price) # I write the 'price' variable in 'render_template' to display it in the html file
if __name__ == "__main__":
app.run(debug=True)
Here is home.html:
<body>
<form action="#" method="POST">
<input type="url" name="asin" id="asin" placeholder="enter the url here" value="{{ request.form.asin }}">
</form>
{% if request.form.asin %}
url: {{ url }} <br>
price: {{ price }} <!-- it displays the default price variable which is 0 whithout changing it value even with changing the url -->
{% endif %}
</body>
Now with this code it displays the price = 0 without changing the value even though I changed the URL, and what I need is to display the price of the product URL.
How do I solve the problem?