UPDATE: 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)
我做错了什么?
答案 0 :(得分: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)