錯誤:local variable '' referenced before assignment

字面上來理解,大概是變量被引用前要先聲明。

曬一下代碼

ARTICLES=''
app=Flask(__name__)
@app.route('/')

def hello_world():
    return '11hello_world'
def getNewsList(Newsurl):
    #global ARTICLES
    res=requests.get(Newsurl)
    soup=BeautifulSoup(res.text,'html.parser')
    artcle=soup.select('#zoomcon font')
    for each in artcle:
        ARTICLES=ARTICLES+each.text
這樣會報錯。因爲ARTICLES是個全局變量。如果要改變全局變量的值,必須先用glabal聲明一下。改後代碼如下。也就是加上一行glabal ARTICLES

ARTICLES=''
app=Flask(__name__)
@app.route('/')

def hello_world():
    return '11hello_world'
def getNewsList(Newsurl):
    global ARTICLES
    res=requests.get(Newsurl)
    soup=BeautifulSoup(res.text,'html.parser')
    artcle=soup.select('#zoomcon font')
    for each in artcle:
        ARTICLES=ARTICLES+each.text

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章