获取网页时出现“NoneType对象不可调用”错误

时间:2012-08-29 09:16:52

标签: python download nonetype

我是python的新手,我写了这段代码

def geturl(url):
    url = urllib.quote(url,'/:')
    log( __name__ ,"Getting url:[%s]" % url)
    try:
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        content    = response.read()
        return_url = response.geturl()
        response.close()
    except Exception, e:
        log( __name__ ,"Failed to get url because %s" % str(e))
        content    = None
        return_url = None
    return(content, return_url)

def myFunc():
    searchurl="http://www.google.com"
    socket.setdefaulttimeout(3)
    content, response_url = geturl(searchurl)
    if content is None:
        log( __name__ , "Content is None!!")
    content = content.replace("string1", "string2")

当我运行它时,我收到此错误:NoneType对象不可调用。 我无法理解为什么......我知道NoneType是None的类型,但我检查“content”变量是否为None而不是。 感谢您的帮助

1 个答案:

答案 0 :(得分:3)

你没有给出错误的一行,但我怀疑以下是错误的:

if content is None:
    log( __name__ , "Content is None!!")
content = content.replace("string1", "string2")

content确实为None时,会发出一个日志,但该函数会一直执行,直到对replace的调用引发异常。