【问题标题】:Scraping: UnboundLocalError: local variable 'content' referenced before assignment抓取:UnboundLocalError:分配前引用的局部变量“内容”
【发布时间】:2019-11-18 13:01:58
【问题描述】:

您好,您能帮我解决一下这段代码吗?我在尝试运行脚本时收到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)

【问题讨论】:

  • content 仅在 for 循环执行时定义。如果没有div class= "singleTipTitle",它将永远不会执行。但请注意,您每次通过每个内部循环都会覆盖该变量;它只会有最后一次执行的价值。我很确定这不是你想要的。
  • 谢谢。没错,我回去重构了代码。

标签: python web-scraping beautifulsoup


【解决方案1】:

想想下面的情况:如果没有有效的内容,你想渲染什么?

发生的情况如下:三个for循环运行,last匹配被写入`content变量。

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

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

【讨论】:

    猜你喜欢
    • 2021-09-12
    • 2017-08-10
    • 2020-01-16
    • 2019-12-05
    • 2017-09-19
    • 2020-09-26
    • 2022-01-02
    • 2019-03-22
    • 2019-01-24
    相关资源
    最近更新 更多