gpt4 book ai didi

python - 我总是收到在分配之前引用局部变量的错误!我该如何解决?

转载 作者:行者123 更新时间:2023-12-03 08:44:17 28 4
gpt4 key购买 nike

感谢您抽出宝贵的时间来帮助我。我在django中编写了一个Web抓取API,但在过去5天中遇到了可怕的错误!奇怪的是,在macOS上绝对没有错误,当我部署到AWS时,它向我抛出了变量引用错误! ubuntu具有python 3.6.8,而macOS具有python 3.6.6

我已经尝试过不同的方法,但是现在我想不起来了!应该返回的抓取数据在macOS上可以正常返回,但是在ubuntu上我被压碎了!请帮忙!

data_list = []
div_class = scrape_driver_2.find(class_ = 'c1_t2i')
daraz_products = scrape_driver.find_all(class_ = 'c2prKC')

for data_fragment in daraz_products: # iterate and find all classes
data_block = data_fragment.text.strip() # Convert code to text
formatted_block = data_block.replace('ADD TO CART', '')

second_iterated_block = formatted_block.replace('%', '')
third_iterated_block = second_iterated_block.replace(')Pakistan', ')-Pakistan')

fourth_iterated_block = third_iterated_block.replace('Pakistan', '-Pakistan')

data_list.append(fourth_iterated_block)
high_data = [{"Timestamp": time_stamp,
"TS Token": ts_token,
"Status": sitrep},
data_list]

return Response({"data": high_data})
engine_initializer.close()

我得到的错误是:
/api/big-budget-filter/中的UnboundLocalError
分配前已引用局部变量“high_data”

最佳答案

将high_data保留在循环之外,并在所有迭代之后进行设置,然后再返回。

data_list = []
div_class = scrape_driver_2.find(class_ = 'c1_t2i')
daraz_products = scrape_driver.find_all(class_ = 'c2prKC')

for data_fragment in daraz_products: # iterate and find all classes
data_block = data_fragment.text.strip() # Convert code to text
formatted_block = data_block.replace('ADD TO CART', '')

second_iterated_block = formatted_block.replace('%', '')
third_iterated_block = second_iterated_block.replace(')Pakistan', ')-Pakistan')

fourth_iterated_block = third_iterated_block.replace('Pakistan', '-Pakistan')

data_list.append(fourth_iterated_block)



high_data = [{"Timestamp": time_stamp,
"TS Token": ts_token,
"Status": sitrep},
data_list]

return Response({"data": high_data})

编辑:根据这篇文章的评论,带有虚拟数据的简化示例版本

data_list = []

daraz_products = ["prod1","prod2","prod3"]

for data_fragment in daraz_products:
data_list.append(data_fragment)

print data_list

data_list将包含daraz_products中的所有产品

关于python - 我总是收到在分配之前引用局部变量的错误!我该如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58118417/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com