报废:UnboundLocalError:分配前引用了本地变量“内容”

您好,请帮助我提供此代码?尝试运行脚本时得到UnboundLocalError: local variable 'content' referenced before assignment 。我尝试了不同的缩进,但仍然出错。

它仅适用于2个for循环,因此for titlefor 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)
braveboy0 回答:报废:UnboundLocalError:分配前引用了本地变量“内容”

请考虑以下情况:如果没有有效内容,您想呈现什么?

会发生以下情况:运行三个for循环,并且将 last 匹配项写入到content变量中。

您使用的某些文件不包含任何匹配项,因此未分配content

函数到达最后一行时,没有content可以传递给render(),因此会出错。

本文链接:https://www.f2er.com/3080889.html

大家都在问