-1

更新: if 语句没有被执行,这很奇怪,因为我在 Django 之外测试了脚本并且只在 Python 中工作。

我知道这个问题已经在这里被问过很多次了,但是我找不到可以帮助我找出错误的答案。这是我得到的错误:

local variable 'what_i_need' referenced before assignment

这是我在 VIEWS 中的代码:

from django.http import HttpResponse
from django.shortcuts import render

from urllib2 import urlopen
from bs4 import BeautifulSoup

def test(request):
    someURL = "https://www.example.com/"
    urlOpen = urlopen(someURL).read()
    soup = BeautifulSoup(urlOpen)
    for x in soup.findAll('span'):
        if 'something' in str(x):
            info = x.get_text()
            info = info.split()
            info = info[0]
            info = info.replace(".", '')
            what_i_need = info
    return HttpResponse(what_i_need)

我究竟做错了什么?

4

1 回答 1

2

问题在于if声明。如果它从未执行,what_i_need则永远不会初始化,因此会出现错误(因为您无法将未初始化的变量传递给HttpResponse)。只需将其初始化为None或类似(根据您的需要)

def test(request):
    someURL = "https://www.example.com/"
    urlOpen = urlopen(someURL).read()
    soup = BeautifulSoup(urlOpen)
    what_i_need = None            # Initialized here
    for x in soup.findAll('span'):
        if 'something' in str(x):
            info = x.get_text()
            info = info.split()
            info = info[0]
            info = info.replace(".", '')
            what_i_need = info
    return HttpResponse(what_i_need)
于 2013-07-09T17:25:43.137 回答