Python Crawler-AttributeError:Crawler实例没有属性';url';

Python Crawler-AttributeError:Crawler实例没有属性';url';,python,class,attributeerror,Python,Class,Attributeerror,我正在尝试学习python中的类: #!/usr/bin/env python # *-* coding: utf-8 *-* import urllib2 from BeautifulSoup import BeautifulSoup as bs class Crawler: def visit(self, url): self.request = urllib2.Request(self.url) self.response = urllib2.

我正在尝试学习python中的类:

#!/usr/bin/env python
# *-* coding: utf-8 *-*

import urllib2
from BeautifulSoup import BeautifulSoup as bs

class Crawler:

    def visit(self, url):
        self.request = urllib2.Request(self.url)
        self.response = urllib2.urlopen(self.request)
        return self.response.read()

if __name__ == "__main__":
    x = Crawler()
    print x.visit("http://google.com/")
当我尝试开始获取错误时:

sigo@sarch ~/sources $ python test.py 
Traceback (most recent call last):
  File "test.py", line 16, in <module>
    print x.visit("http://google.com/")
  File "test.py", line 10, in visit
    self.request = urllib2.Request(self.url)
AttributeError: Crawler instance has no attribute 'url'
sigo@sarch~/sources$python test.py
回溯(最近一次呼叫最后一次):
文件“test.py”,第16行,在
打印x.visit(“http://google.com/")
访问中第10行的文件“test.py”
self.request=urllib2.request(self.url)
AttributeError:爬虫程序实例没有属性“url”

我做错了什么?

您说的是
self.url
,它指的是爬虫类的
url
属性,该属性不存在。您只需要使用
url
,因为这是
visit()
函数参数中变量的名称。

您说的是
self.url
,它指的是爬虫类的
url
属性,该属性不存在。您只需使用
url
,因为这是
visit()
函数参数中变量的名称。

谢谢您的编辑!实际上,类实例的
url
属性(即
self.url
)不存在,函数局部变量
url
存在。感谢您的编辑!实际上,类实例的
url
属性(即
self.url
)不存在,函数局部变量
url
存在。