python - 获取 UnboundLocalError:在网络抓取应用程序中分配之前引用的局部变量“价格”
问题描述
我是 python 和 Flask 的新手,我正在使用 Python3 和 Flask 构建一个网络爬虫应用程序。但我对这个错误有一个问题:“UnboundLocalError:分配前引用的局部变量'价格'”。我不知道我在程序中做错了什么来得到这个错误。
我用初始变量'a = 0'尝试了'global a'并编写了代码,但即使我更改了URL,它也只显示初始变量'0'而没有任何变化。
这是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)
这是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>
现在使用此代码,即使我更改了 URL,它也会显示价格 = 0 而不会更改值,而我需要的是显示产品 URL 的价格。
我该如何解决这个问题?
解决方案
- 使用全局变量来向函数发送值是个坏主意,它应该接受默认参数 func_name(default_price = value)。
- 在打印之前不需要使用 global,因为名为 'price' 的变量在包含范围内,当你想从外部范围更改变量时,需要使用 'global' 关键字,即:当你这样做
price = soup.select_one("#priceblock_ourprice").text
并再次,这是非常不鼓励的。请参阅以下帖子:在 Python 中使用“全局”关键字 - 我的猜测是,当您使用 app.run 运行代码时(我不确定),它是在与您期望运行的范围不同的范围内创建的(这是您拥有的模块的范围)给定)。如果我是你,我会在“全球价格”语句之前添加一个断点,看看是否显示了可变价格。如果不是,那么框架将在不同的范围内运行您的代码,该范围无法识别您的全局变量(无论哪种方式,您都应该将其作为参数传递给函数)。
推荐阅读
- javascript - 将html转换为pdf后节点返回字节数组
- python - AWS lambda:调用 HeadObject 操作时发生错误 (404):未找到
- c++ - 编译 LLVM IR 时使用 LLVM 头文件
- python - 模块“googlefinance”pylint 中没有名称“getQuotes”(模块中没有名称)
- javascript - 使用“未知”数据更新部分界面
- django - 进行相关查询?
- c++ - 如何在 c++ shared_ptr 中使用 lambda 作为删除器来创建对象缓存?
- google-bigquery - 即使源为空,查询仍然会花费我们
- javascript - 如何将 CSV 转换为 JS 对象数组
- batch-file - 如何使用新修改的系统环境启动 Windows 7 控制台?