0

当我运行以下功能时:

def checkChange():
    for user in userLinks:
        url = userLinks[user]
        response = urllib2.urlopen(url)  
        html = response.read()

我明白了

Traceback (most recent call last):
  File "InStockBot.py", line 34, in <module>
    checkChange()
  File "InStockBot.py", line 24, in checkChange
    html = response.read()
UnboundLocalError: local variable 'response' referenced before assignment

这对我来说毫无意义。我没有全局 var 响应。我希望它正常工作如下。

>>> url="http://google.com"
>>> response = urllib2.urlopen(url)  
>>> html = response.read()
>>> html
'<!doctype html>

有谁知道我为什么会收到这个错误?

4

2 回答 2

1

您的代码没有正确缩进。将其更改为此,它会工作(可能不像预期的那样,但它会工作):

for user in userLinks:
    url = userLinks[user]
    response = urllib2.urlopen(url)  
    html = response.read()

    if userSources[user] != html:
        del userSources[user]
        del userLinks[user]
        api.PostDirectMessage(user,'It appears the page has updated! Your item may be back in stock!')

发生错误是因为您responsefor循环中定义,但如果循环没有运行(即userLinks == []),则永远不会设置该变量。

于 2013-01-12T03:35:37.187 回答
1

您正在混合制表符和空格。查看您粘贴的原始代码:

'    def checkChange():'
'    \tfor user in userLinks:'
'    \t\turl = userLinks[user]'
'    \t\tresponse = urllib2.urlopen(url)  '
'            html = response.read()'

您可以在最后一行看到开关。实际上,这意味着该html = response.read()行没有像您想象的那样缩进,这意味着如果userLinks为空,您将得到:

Traceback (most recent call last):
  File "inde.py", line 10, in <module>
    checkChange()
  File "inde.py", line 5, in checkChange
    html = response.read()
UnboundLocalError: local variable 'response' referenced before assignment

运行您的代码python -tt yourprogramname.py以确认这一点,并切换到始终使用四空格制表符。

于 2013-01-12T03:36:25.823 回答