【发布时间】:2019-11-18 13:01:58
【问题描述】:
您好,您能帮我解决一下这段代码吗?我在尝试运行脚本时收到UnboundLocalError: local variable 'content' referenced before assignment
。我尝试了不同的缩进,但仍然出错。
它只适用于 2 个 for 循环,所以 for title 和 for price 非常感谢
def tickets(request):
ticket_offer = []
url = 'some random URL'
result = requests.get(url)
content_data = BeautifulSoup(result.content, features="html.parser")
for title in content_data.find_all('div', {"class": "singleTipTitle"}):
for price in title.find_all('span', {"class": "price"}):
for time in price.find_all('div', {"class": "meta"}):
ticket = {
'title': title.text,
'price': price.text,
'time': time.text
}
ticket_offer.append(ticket)
content = {'ticket_offer': ticket_offer}
print(ticket_offer)
return render(request, 'tickets/tickets.html', content)
【问题讨论】:
-
content仅在 for 循环执行时定义。如果没有div class= "singleTipTitle",它将永远不会执行。但请注意,您每次通过每个内部循环都会覆盖该变量;它只会有最后一次执行的价值。我很确定这不是你想要的。 -
谢谢。没错,我回去重构了代码。
标签: python web-scraping beautifulsoup